es6.js 4.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783
  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. var EffectFallbacks = /** @class */ (function () {
  6. function EffectFallbacks() {
  7. this._defines = {};
  8. this._currentRank = 32;
  9. this._maxRank = -1;
  10. }
  11. EffectFallbacks.prototype.unBindMesh = function () {
  12. this._mesh = null;
  13. };
  14. EffectFallbacks.prototype.addFallback = function (rank, define) {
  15. if (!this._defines[rank]) {
  16. if (rank < this._currentRank) {
  17. this._currentRank = rank;
  18. }
  19. if (rank > this._maxRank) {
  20. this._maxRank = rank;
  21. }
  22. this._defines[rank] = new Array();
  23. }
  24. this._defines[rank].push(define);
  25. };
  26. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  27. this._mesh = mesh;
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. };
  35. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  36. get: function () {
  37. return this._currentRank <= this._maxRank;
  38. },
  39. enumerable: true,
  40. configurable: true
  41. });
  42. EffectFallbacks.prototype.reduce = function (currentDefines) {
  43. // First we try to switch to CPU skinning
  44. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  45. this._mesh.computeBonesUsingShaders = false;
  46. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  47. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  48. var scene = this._mesh.getScene();
  49. for (var index = 0; index < scene.meshes.length; index++) {
  50. var otherMesh = scene.meshes[index];
  51. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  52. otherMesh.computeBonesUsingShaders = false;
  53. }
  54. }
  55. }
  56. else {
  57. var currentFallbacks = this._defines[this._currentRank];
  58. if (currentFallbacks) {
  59. for (var index = 0; index < currentFallbacks.length; index++) {
  60. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  61. }
  62. }
  63. this._currentRank++;
  64. }
  65. return currentDefines;
  66. };
  67. return EffectFallbacks;
  68. }());
  69. BABYLON.EffectFallbacks = EffectFallbacks;
  70. var EffectCreationOptions = /** @class */ (function () {
  71. function EffectCreationOptions() {
  72. }
  73. return EffectCreationOptions;
  74. }());
  75. BABYLON.EffectCreationOptions = EffectCreationOptions;
  76. var Effect = /** @class */ (function () {
  77. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  78. if (samplers === void 0) { samplers = null; }
  79. if (defines === void 0) { defines = null; }
  80. if (fallbacks === void 0) { fallbacks = null; }
  81. if (onCompiled === void 0) { onCompiled = null; }
  82. if (onError === void 0) { onError = null; }
  83. var _this = this;
  84. this.uniqueId = 0;
  85. this.onCompileObservable = new BABYLON.Observable();
  86. this.onErrorObservable = new BABYLON.Observable();
  87. this.onBindObservable = new BABYLON.Observable();
  88. this._uniformBuffersNames = {};
  89. this._isReady = false;
  90. this._compilationError = "";
  91. this.name = baseName;
  92. if (attributesNamesOrOptions.attributes) {
  93. var options = attributesNamesOrOptions;
  94. this._engine = uniformsNamesOrEngine;
  95. this._attributesNames = options.attributes;
  96. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  97. this._samplers = options.samplers;
  98. this.defines = options.defines;
  99. this.onError = options.onError;
  100. this.onCompiled = options.onCompiled;
  101. this._fallbacks = options.fallbacks;
  102. this._indexParameters = options.indexParameters;
  103. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  104. if (options.uniformBuffersNames) {
  105. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  106. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  107. }
  108. }
  109. }
  110. else {
  111. this._engine = engine;
  112. this.defines = defines;
  113. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  114. this._samplers = samplers;
  115. this._attributesNames = attributesNamesOrOptions;
  116. this.onError = onError;
  117. this.onCompiled = onCompiled;
  118. this._indexParameters = indexParameters;
  119. this._fallbacks = fallbacks;
  120. }
  121. this.uniqueId = Effect._uniqueIdSeed++;
  122. var vertexSource;
  123. var fragmentSource;
  124. if (baseName.vertexElement) {
  125. vertexSource = document.getElementById(baseName.vertexElement);
  126. if (!vertexSource) {
  127. vertexSource = baseName.vertexElement;
  128. }
  129. }
  130. else {
  131. vertexSource = baseName.vertex || baseName;
  132. }
  133. if (baseName.fragmentElement) {
  134. fragmentSource = document.getElementById(baseName.fragmentElement);
  135. if (!fragmentSource) {
  136. fragmentSource = baseName.fragmentElement;
  137. }
  138. }
  139. else {
  140. fragmentSource = baseName.fragment || baseName;
  141. }
  142. var finalVertexCode;
  143. this._loadVertexShaderAsync(vertexSource)
  144. .then(function (vertexCode) {
  145. return _this._processIncludesAsync(vertexCode);
  146. })
  147. .then(function (vertexCodeWithIncludes) {
  148. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  149. return _this._loadFragmentShaderAsync(fragmentSource);
  150. })
  151. .then(function (fragmentCode) {
  152. return _this._processIncludesAsync(fragmentCode);
  153. })
  154. .then(function (fragmentCodeWithIncludes) {
  155. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  156. if (baseName) {
  157. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  158. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  159. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  160. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  161. }
  162. else {
  163. _this._vertexSourceCode = finalVertexCode;
  164. _this._fragmentSourceCode = migratedFragmentCode;
  165. }
  166. _this._prepareEffect();
  167. });
  168. }
  169. Object.defineProperty(Effect.prototype, "key", {
  170. get: function () {
  171. return this._key;
  172. },
  173. enumerable: true,
  174. configurable: true
  175. });
  176. // Properties
  177. Effect.prototype.isReady = function () {
  178. return this._isReady;
  179. };
  180. Effect.prototype.getEngine = function () {
  181. return this._engine;
  182. };
  183. Effect.prototype.getProgram = function () {
  184. return this._program;
  185. };
  186. Effect.prototype.getAttributesNames = function () {
  187. return this._attributesNames;
  188. };
  189. Effect.prototype.getAttributeLocation = function (index) {
  190. return this._attributes[index];
  191. };
  192. Effect.prototype.getAttributeLocationByName = function (name) {
  193. var index = this._attributesNames.indexOf(name);
  194. return this._attributes[index];
  195. };
  196. Effect.prototype.getAttributesCount = function () {
  197. return this._attributes.length;
  198. };
  199. Effect.prototype.getUniformIndex = function (uniformName) {
  200. return this._uniformsNames.indexOf(uniformName);
  201. };
  202. Effect.prototype.getUniform = function (uniformName) {
  203. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  204. };
  205. Effect.prototype.getSamplers = function () {
  206. return this._samplers;
  207. };
  208. Effect.prototype.getCompilationError = function () {
  209. return this._compilationError;
  210. };
  211. // Methods
  212. Effect.prototype.executeWhenCompiled = function (func) {
  213. if (this.isReady()) {
  214. func(this);
  215. return;
  216. }
  217. this.onCompileObservable.add(function (effect) {
  218. func(effect);
  219. });
  220. };
  221. /** @ignore */
  222. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  223. if (BABYLON.Tools.IsWindowObjectExist()) {
  224. // DOM element ?
  225. if (vertex instanceof HTMLElement) {
  226. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  227. return Promise.resolve(vertexCode);
  228. }
  229. }
  230. // Base64 encoded ?
  231. if (vertex.substr(0, 7) === "base64:") {
  232. var vertexBinary = window.atob(vertex.substr(7));
  233. return Promise.resolve(vertexBinary);
  234. }
  235. // Is in local store ?
  236. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  237. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  238. }
  239. var vertexShaderUrl;
  240. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  241. vertexShaderUrl = vertex;
  242. }
  243. else {
  244. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  245. }
  246. // Vertex shader
  247. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  248. };
  249. /** @ignore */
  250. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  251. if (BABYLON.Tools.IsWindowObjectExist()) {
  252. // DOM element ?
  253. if (fragment instanceof HTMLElement) {
  254. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  255. return Promise.resolve(fragmentCode);
  256. }
  257. }
  258. // Base64 encoded ?
  259. if (fragment.substr(0, 7) === "base64:") {
  260. var fragmentBinary = window.atob(fragment.substr(7));
  261. return Promise.resolve(fragmentBinary);
  262. }
  263. // Is in local store ?
  264. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  265. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  266. }
  267. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  268. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  269. }
  270. var fragmentShaderUrl;
  271. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  272. fragmentShaderUrl = fragment;
  273. }
  274. else {
  275. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  276. }
  277. // Fragment shader
  278. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  279. };
  280. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  281. // Rebuild shaders source code
  282. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  283. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  284. vertexCode = prefix + vertexCode;
  285. fragmentCode = prefix + fragmentCode;
  286. // Number lines of shaders source code
  287. var i = 2;
  288. var regex = /\n/gm;
  289. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  290. i = 2;
  291. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  292. // Dump shaders name and formatted source code
  293. if (this.name.vertexElement) {
  294. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  295. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  296. }
  297. else if (this.name.vertex) {
  298. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  299. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  300. }
  301. else {
  302. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  303. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  304. }
  305. };
  306. ;
  307. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  308. var preparedSourceCode = this._processPrecision(sourceCode);
  309. if (this._engine.webGLVersion == 1) {
  310. return preparedSourceCode;
  311. }
  312. // Already converted
  313. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  314. return preparedSourceCode.replace("#version 300 es", "");
  315. }
  316. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  317. // Remove extensions
  318. // #extension GL_OES_standard_derivatives : enable
  319. // #extension GL_EXT_shader_texture_lod : enable
  320. // #extension GL_EXT_frag_depth : enable
  321. // #extension GL_EXT_draw_buffers : require
  322. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  323. var result = preparedSourceCode.replace(regex, "");
  324. // Migrate to GLSL v300
  325. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  326. result = result.replace(/attribute[ \t]/g, "in ");
  327. result = result.replace(/[ \t]attribute/g, " in");
  328. if (isFragment) {
  329. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  330. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  331. result = result.replace(/texture2D\s*\(/g, "texture(");
  332. result = result.replace(/textureCube\s*\(/g, "texture(");
  333. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  334. result = result.replace(/gl_FragColor/g, "glFragColor");
  335. result = result.replace(/gl_FragData/g, "glFragData");
  336. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  337. }
  338. return result;
  339. };
  340. Effect.prototype._processIncludesAsync = function (sourceCode) {
  341. var _this = this;
  342. return new Promise(function (resolve, reject) {
  343. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  344. var match = regex.exec(sourceCode);
  345. var returnValue = sourceCode;
  346. while (match != null) {
  347. var includeFile = match[1];
  348. // Uniform declaration
  349. if (includeFile.indexOf("__decl__") !== -1) {
  350. includeFile = includeFile.replace(/__decl__/, "");
  351. if (_this._engine.supportsUniformBuffers) {
  352. includeFile = includeFile.replace(/Vertex/, "Ubo");
  353. includeFile = includeFile.replace(/Fragment/, "Ubo");
  354. }
  355. includeFile = includeFile + "Declaration";
  356. }
  357. if (Effect.IncludesShadersStore[includeFile]) {
  358. // Substitution
  359. var includeContent = Effect.IncludesShadersStore[includeFile];
  360. if (match[2]) {
  361. var splits = match[3].split(",");
  362. for (var index = 0; index < splits.length; index += 2) {
  363. var source = new RegExp(splits[index], "g");
  364. var dest = splits[index + 1];
  365. includeContent = includeContent.replace(source, dest);
  366. }
  367. }
  368. if (match[4]) {
  369. var indexString = match[5];
  370. if (indexString.indexOf("..") !== -1) {
  371. var indexSplits = indexString.split("..");
  372. var minIndex = parseInt(indexSplits[0]);
  373. var maxIndex = parseInt(indexSplits[1]);
  374. var sourceIncludeContent = includeContent.slice(0);
  375. includeContent = "";
  376. if (isNaN(maxIndex)) {
  377. maxIndex = _this._indexParameters[indexSplits[1]];
  378. }
  379. for (var i = minIndex; i < maxIndex; i++) {
  380. if (!_this._engine.supportsUniformBuffers) {
  381. // Ubo replacement
  382. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  383. return p1 + "{X}";
  384. });
  385. }
  386. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  387. }
  388. }
  389. else {
  390. if (!_this._engine.supportsUniformBuffers) {
  391. // Ubo replacement
  392. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  393. return p1 + "{X}";
  394. });
  395. }
  396. includeContent = includeContent.replace(/\{X\}/g, indexString);
  397. }
  398. }
  399. // Replace
  400. returnValue = returnValue.replace(match[0], includeContent);
  401. }
  402. else {
  403. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  404. _this._engine._loadFileAsync(includeShaderUrl)
  405. .then(function (fileContent) {
  406. Effect.IncludesShadersStore[includeFile] = fileContent;
  407. return _this._processIncludesAsync(returnValue);
  408. })
  409. .then(function (returnValue) {
  410. resolve(returnValue);
  411. });
  412. return;
  413. }
  414. match = regex.exec(sourceCode);
  415. }
  416. resolve(returnValue);
  417. });
  418. };
  419. Effect.prototype._processPrecision = function (source) {
  420. if (source.indexOf("precision highp float") === -1) {
  421. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  422. source = "precision mediump float;\n" + source;
  423. }
  424. else {
  425. source = "precision highp float;\n" + source;
  426. }
  427. }
  428. else {
  429. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  430. source = source.replace("precision highp float", "precision mediump float");
  431. }
  432. }
  433. return source;
  434. };
  435. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  436. var _this = this;
  437. this._isReady = false;
  438. this._vertexSourceCodeOverride = vertexSourceCode;
  439. this._fragmentSourceCodeOverride = fragmentSourceCode;
  440. this.onError = function (effect, error) {
  441. if (onError) {
  442. onError(error);
  443. }
  444. };
  445. this.onCompiled = function () {
  446. var scenes = _this.getEngine().scenes;
  447. for (var i = 0; i < scenes.length; i++) {
  448. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  449. }
  450. if (onCompiled) {
  451. onCompiled(_this._program);
  452. }
  453. };
  454. this._fallbacks = null;
  455. this._prepareEffect();
  456. };
  457. Effect.prototype.getSpecificUniformLocations = function (names) {
  458. var engine = this._engine;
  459. return engine.getUniforms(this._program, names);
  460. };
  461. Effect.prototype._prepareEffect = function () {
  462. var attributesNames = this._attributesNames;
  463. var defines = this.defines;
  464. var fallbacks = this._fallbacks;
  465. this._valueCache = {};
  466. var previousProgram = this._program;
  467. try {
  468. var engine = this._engine;
  469. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  470. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  471. }
  472. else {
  473. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  474. }
  475. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  476. if (engine.supportsUniformBuffers) {
  477. for (var name in this._uniformBuffersNames) {
  478. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  479. }
  480. }
  481. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  482. this._attributes = engine.getAttributes(this._program, attributesNames);
  483. var index;
  484. for (index = 0; index < this._samplers.length; index++) {
  485. var sampler = this.getUniform(this._samplers[index]);
  486. if (sampler == null) {
  487. this._samplers.splice(index, 1);
  488. index--;
  489. }
  490. }
  491. engine.bindSamplers(this);
  492. this._compilationError = "";
  493. this._isReady = true;
  494. if (this.onCompiled) {
  495. this.onCompiled(this);
  496. }
  497. this.onCompileObservable.notifyObservers(this);
  498. this.onCompileObservable.clear();
  499. // Unbind mesh reference in fallbacks
  500. if (this._fallbacks) {
  501. this._fallbacks.unBindMesh();
  502. }
  503. if (previousProgram) {
  504. this.getEngine()._deleteProgram(previousProgram);
  505. }
  506. }
  507. catch (e) {
  508. this._compilationError = e.message;
  509. // Let's go through fallbacks then
  510. BABYLON.Tools.Error("Unable to compile effect:");
  511. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  512. return " " + uniform;
  513. }));
  514. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  515. return " " + attribute;
  516. }));
  517. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  518. BABYLON.Tools.Error("Error: " + this._compilationError);
  519. if (previousProgram) {
  520. this._program = previousProgram;
  521. this._isReady = true;
  522. if (this.onError) {
  523. this.onError(this, this._compilationError);
  524. }
  525. this.onErrorObservable.notifyObservers(this);
  526. }
  527. if (fallbacks && fallbacks.isMoreFallbacks) {
  528. BABYLON.Tools.Error("Trying next fallback.");
  529. this.defines = fallbacks.reduce(this.defines);
  530. this._prepareEffect();
  531. }
  532. else {
  533. if (this.onError) {
  534. this.onError(this, this._compilationError);
  535. }
  536. this.onErrorObservable.notifyObservers(this);
  537. this.onErrorObservable.clear();
  538. // Unbind mesh reference in fallbacks
  539. if (this._fallbacks) {
  540. this._fallbacks.unBindMesh();
  541. }
  542. }
  543. }
  544. };
  545. Object.defineProperty(Effect.prototype, "isSupported", {
  546. get: function () {
  547. return this._compilationError === "";
  548. },
  549. enumerable: true,
  550. configurable: true
  551. });
  552. Effect.prototype._bindTexture = function (channel, texture) {
  553. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  554. };
  555. Effect.prototype.setTexture = function (channel, texture) {
  556. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  557. };
  558. Effect.prototype.setTextureArray = function (channel, textures) {
  559. if (this._samplers.indexOf(channel + "Ex") === -1) {
  560. var initialPos = this._samplers.indexOf(channel);
  561. for (var index = 1; index < textures.length; index++) {
  562. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  563. }
  564. }
  565. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  566. };
  567. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  568. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  569. };
  570. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  571. var cache = this._valueCache[uniformName];
  572. var flag = matrix.updateFlag;
  573. if (cache !== undefined && cache === flag) {
  574. return false;
  575. }
  576. this._valueCache[uniformName] = flag;
  577. return true;
  578. };
  579. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  580. var cache = this._valueCache[uniformName];
  581. if (!cache) {
  582. cache = [x, y];
  583. this._valueCache[uniformName] = cache;
  584. return true;
  585. }
  586. var changed = false;
  587. if (cache[0] !== x) {
  588. cache[0] = x;
  589. changed = true;
  590. }
  591. if (cache[1] !== y) {
  592. cache[1] = y;
  593. changed = true;
  594. }
  595. return changed;
  596. };
  597. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  598. var cache = this._valueCache[uniformName];
  599. if (!cache) {
  600. cache = [x, y, z];
  601. this._valueCache[uniformName] = cache;
  602. return true;
  603. }
  604. var changed = false;
  605. if (cache[0] !== x) {
  606. cache[0] = x;
  607. changed = true;
  608. }
  609. if (cache[1] !== y) {
  610. cache[1] = y;
  611. changed = true;
  612. }
  613. if (cache[2] !== z) {
  614. cache[2] = z;
  615. changed = true;
  616. }
  617. return changed;
  618. };
  619. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  620. var cache = this._valueCache[uniformName];
  621. if (!cache) {
  622. cache = [x, y, z, w];
  623. this._valueCache[uniformName] = cache;
  624. return true;
  625. }
  626. var changed = false;
  627. if (cache[0] !== x) {
  628. cache[0] = x;
  629. changed = true;
  630. }
  631. if (cache[1] !== y) {
  632. cache[1] = y;
  633. changed = true;
  634. }
  635. if (cache[2] !== z) {
  636. cache[2] = z;
  637. changed = true;
  638. }
  639. if (cache[3] !== w) {
  640. cache[3] = w;
  641. changed = true;
  642. }
  643. return changed;
  644. };
  645. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  646. var bufferName = this._uniformBuffersNames[name];
  647. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  648. return;
  649. }
  650. Effect._baseCache[bufferName] = buffer;
  651. this._engine.bindUniformBufferBase(buffer, bufferName);
  652. };
  653. Effect.prototype.bindUniformBlock = function (blockName, index) {
  654. this._engine.bindUniformBlock(this._program, blockName, index);
  655. };
  656. Effect.prototype.setInt = function (uniformName, value) {
  657. var cache = this._valueCache[uniformName];
  658. if (cache !== undefined && cache === value)
  659. return this;
  660. this._valueCache[uniformName] = value;
  661. this._engine.setInt(this.getUniform(uniformName), value);
  662. return this;
  663. };
  664. Effect.prototype.setIntArray = function (uniformName, array) {
  665. this._valueCache[uniformName] = null;
  666. this._engine.setIntArray(this.getUniform(uniformName), array);
  667. return this;
  668. };
  669. Effect.prototype.setIntArray2 = function (uniformName, array) {
  670. this._valueCache[uniformName] = null;
  671. this._engine.setIntArray2(this.getUniform(uniformName), array);
  672. return this;
  673. };
  674. Effect.prototype.setIntArray3 = function (uniformName, array) {
  675. this._valueCache[uniformName] = null;
  676. this._engine.setIntArray3(this.getUniform(uniformName), array);
  677. return this;
  678. };
  679. Effect.prototype.setIntArray4 = function (uniformName, array) {
  680. this._valueCache[uniformName] = null;
  681. this._engine.setIntArray4(this.getUniform(uniformName), array);
  682. return this;
  683. };
  684. Effect.prototype.setFloatArray = function (uniformName, array) {
  685. this._valueCache[uniformName] = null;
  686. this._engine.setFloatArray(this.getUniform(uniformName), array);
  687. return this;
  688. };
  689. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  690. this._valueCache[uniformName] = null;
  691. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  692. return this;
  693. };
  694. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  695. this._valueCache[uniformName] = null;
  696. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  697. return this;
  698. };
  699. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  700. this._valueCache[uniformName] = null;
  701. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  702. return this;
  703. };
  704. Effect.prototype.setArray = function (uniformName, array) {
  705. this._valueCache[uniformName] = null;
  706. this._engine.setArray(this.getUniform(uniformName), array);
  707. return this;
  708. };
  709. Effect.prototype.setArray2 = function (uniformName, array) {
  710. this._valueCache[uniformName] = null;
  711. this._engine.setArray2(this.getUniform(uniformName), array);
  712. return this;
  713. };
  714. Effect.prototype.setArray3 = function (uniformName, array) {
  715. this._valueCache[uniformName] = null;
  716. this._engine.setArray3(this.getUniform(uniformName), array);
  717. return this;
  718. };
  719. Effect.prototype.setArray4 = function (uniformName, array) {
  720. this._valueCache[uniformName] = null;
  721. this._engine.setArray4(this.getUniform(uniformName), array);
  722. return this;
  723. };
  724. Effect.prototype.setMatrices = function (uniformName, matrices) {
  725. if (!matrices) {
  726. return this;
  727. }
  728. this._valueCache[uniformName] = null;
  729. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  730. return this;
  731. };
  732. Effect.prototype.setMatrix = function (uniformName, matrix) {
  733. if (this._cacheMatrix(uniformName, matrix)) {
  734. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  735. }
  736. return this;
  737. };
  738. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  739. this._valueCache[uniformName] = null;
  740. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  741. return this;
  742. };
  743. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  744. this._valueCache[uniformName] = null;
  745. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  746. return this;
  747. };
  748. Effect.prototype.setFloat = function (uniformName, value) {
  749. var cache = this._valueCache[uniformName];
  750. if (cache !== undefined && cache === value)
  751. return this;
  752. this._valueCache[uniformName] = value;
  753. this._engine.setFloat(this.getUniform(uniformName), value);
  754. return this;
  755. };
  756. Effect.prototype.setBool = function (uniformName, bool) {
  757. var cache = this._valueCache[uniformName];
  758. if (cache !== undefined && cache === bool)
  759. return this;
  760. this._valueCache[uniformName] = bool;
  761. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  762. return this;
  763. };
  764. Effect.prototype.setVector2 = function (uniformName, vector2) {
  765. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  766. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  767. }
  768. return this;
  769. };
  770. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  771. if (this._cacheFloat2(uniformName, x, y)) {
  772. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  773. }
  774. return this;
  775. };
  776. Effect.prototype.setVector3 = function (uniformName, vector3) {
  777. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  778. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  783. if (this._cacheFloat3(uniformName, x, y, z)) {
  784. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector4 = function (uniformName, vector4) {
  789. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  790. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  795. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  796. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setColor3 = function (uniformName, color3) {
  801. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  802. this._engine.setColor3(this.getUniform(uniformName), color3);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  807. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  808. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  809. }
  810. return this;
  811. };
  812. Effect.ResetCache = function () {
  813. Effect._baseCache = {};
  814. };
  815. Effect._uniqueIdSeed = 0;
  816. Effect._baseCache = {};
  817. // Statics
  818. Effect.ShadersStore = {};
  819. Effect.IncludesShadersStore = {};
  820. return Effect;
  821. }());
  822. BABYLON.Effect = Effect;
  823. })(BABYLON || (BABYLON = {}));
  824. //# sourceMappingURL=babylon.effect.js.map
  825. //# sourceMappingURL=babylon.types.js.map
  826. var BABYLON;
  827. (function (BABYLON) {
  828. var KeyboardEventTypes = /** @class */ (function () {
  829. function KeyboardEventTypes() {
  830. }
  831. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  832. get: function () {
  833. return KeyboardEventTypes._KEYDOWN;
  834. },
  835. enumerable: true,
  836. configurable: true
  837. });
  838. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  839. get: function () {
  840. return KeyboardEventTypes._KEYUP;
  841. },
  842. enumerable: true,
  843. configurable: true
  844. });
  845. KeyboardEventTypes._KEYDOWN = 0x01;
  846. KeyboardEventTypes._KEYUP = 0x02;
  847. return KeyboardEventTypes;
  848. }());
  849. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  850. var KeyboardInfo = /** @class */ (function () {
  851. function KeyboardInfo(type, event) {
  852. this.type = type;
  853. this.event = event;
  854. }
  855. return KeyboardInfo;
  856. }());
  857. BABYLON.KeyboardInfo = KeyboardInfo;
  858. /**
  859. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  860. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  861. */
  862. var KeyboardInfoPre = /** @class */ (function (_super) {
  863. __extends(KeyboardInfoPre, _super);
  864. function KeyboardInfoPre(type, event) {
  865. var _this = _super.call(this, type, event) || this;
  866. _this.skipOnPointerObservable = false;
  867. return _this;
  868. }
  869. return KeyboardInfoPre;
  870. }(KeyboardInfo));
  871. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  872. })(BABYLON || (BABYLON = {}));
  873. //# sourceMappingURL=babylon.keyboardEvents.js.map
  874. var BABYLON;
  875. (function (BABYLON) {
  876. var PointerEventTypes = /** @class */ (function () {
  877. function PointerEventTypes() {
  878. }
  879. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  880. get: function () {
  881. return PointerEventTypes._POINTERDOWN;
  882. },
  883. enumerable: true,
  884. configurable: true
  885. });
  886. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  887. get: function () {
  888. return PointerEventTypes._POINTERUP;
  889. },
  890. enumerable: true,
  891. configurable: true
  892. });
  893. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  894. get: function () {
  895. return PointerEventTypes._POINTERMOVE;
  896. },
  897. enumerable: true,
  898. configurable: true
  899. });
  900. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  901. get: function () {
  902. return PointerEventTypes._POINTERWHEEL;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  908. get: function () {
  909. return PointerEventTypes._POINTERPICK;
  910. },
  911. enumerable: true,
  912. configurable: true
  913. });
  914. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  915. get: function () {
  916. return PointerEventTypes._POINTERTAP;
  917. },
  918. enumerable: true,
  919. configurable: true
  920. });
  921. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  922. get: function () {
  923. return PointerEventTypes._POINTERDOUBLETAP;
  924. },
  925. enumerable: true,
  926. configurable: true
  927. });
  928. PointerEventTypes._POINTERDOWN = 0x01;
  929. PointerEventTypes._POINTERUP = 0x02;
  930. PointerEventTypes._POINTERMOVE = 0x04;
  931. PointerEventTypes._POINTERWHEEL = 0x08;
  932. PointerEventTypes._POINTERPICK = 0x10;
  933. PointerEventTypes._POINTERTAP = 0x20;
  934. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  935. return PointerEventTypes;
  936. }());
  937. BABYLON.PointerEventTypes = PointerEventTypes;
  938. var PointerInfoBase = /** @class */ (function () {
  939. function PointerInfoBase(type, event) {
  940. this.type = type;
  941. this.event = event;
  942. }
  943. return PointerInfoBase;
  944. }());
  945. BABYLON.PointerInfoBase = PointerInfoBase;
  946. /**
  947. * This class is used to store pointer related info for the onPrePointerObservable event.
  948. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  949. */
  950. var PointerInfoPre = /** @class */ (function (_super) {
  951. __extends(PointerInfoPre, _super);
  952. function PointerInfoPre(type, event, localX, localY) {
  953. var _this = _super.call(this, type, event) || this;
  954. _this.skipOnPointerObservable = false;
  955. _this.localPosition = new BABYLON.Vector2(localX, localY);
  956. return _this;
  957. }
  958. return PointerInfoPre;
  959. }(PointerInfoBase));
  960. BABYLON.PointerInfoPre = PointerInfoPre;
  961. /**
  962. * This type contains all the data related to a pointer event in Babylon.js.
  963. * 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.
  964. */
  965. var PointerInfo = /** @class */ (function (_super) {
  966. __extends(PointerInfo, _super);
  967. function PointerInfo(type, event, pickInfo) {
  968. var _this = _super.call(this, type, event) || this;
  969. _this.pickInfo = pickInfo;
  970. return _this;
  971. }
  972. return PointerInfo;
  973. }(PointerInfoBase));
  974. BABYLON.PointerInfo = PointerInfo;
  975. })(BABYLON || (BABYLON = {}));
  976. //# sourceMappingURL=babylon.pointerEvents.js.map
  977. var BABYLON;
  978. (function (BABYLON) {
  979. BABYLON.ToGammaSpace = 1 / 2.2;
  980. BABYLON.ToLinearSpace = 2.2;
  981. BABYLON.Epsilon = 0.001;
  982. /**
  983. * Class used to hold a RBG color
  984. */
  985. var Color3 = /** @class */ (function () {
  986. /**
  987. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  988. * @param r defines the red component (between 0 and 1, default is 0)
  989. * @param g defines the green component (between 0 and 1, default is 0)
  990. * @param b defines the blue component (between 0 and 1, default is 0)
  991. */
  992. function Color3(
  993. /**
  994. * Defines the red component (between 0 and 1, default is 0)
  995. */
  996. r,
  997. /**
  998. * Defines the green component (between 0 and 1, default is 0)
  999. */
  1000. g,
  1001. /**
  1002. * Defines the blue component (between 0 and 1, default is 0)
  1003. */
  1004. b) {
  1005. if (r === void 0) { r = 0; }
  1006. if (g === void 0) { g = 0; }
  1007. if (b === void 0) { b = 0; }
  1008. this.r = r;
  1009. this.g = g;
  1010. this.b = b;
  1011. }
  1012. /**
  1013. * Creates a string with the Color3 current values
  1014. * @returns the string representation of the Color3 object
  1015. */
  1016. Color3.prototype.toString = function () {
  1017. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1018. };
  1019. /**
  1020. * Returns the string "Color3"
  1021. * @returns "Color3"
  1022. */
  1023. Color3.prototype.getClassName = function () {
  1024. return "Color3";
  1025. };
  1026. /**
  1027. * Compute the Color3 hash code
  1028. * @returns an unique number that can be used to hash Color3 objects
  1029. */
  1030. Color3.prototype.getHashCode = function () {
  1031. var hash = this.r || 0;
  1032. hash = (hash * 397) ^ (this.g || 0);
  1033. hash = (hash * 397) ^ (this.b || 0);
  1034. return hash;
  1035. };
  1036. // Operators
  1037. /**
  1038. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1039. * @param array defines the array where to store the r,g,b components
  1040. * @param index defines an optional index in the target array to define where to start storing values
  1041. * @returns the current Color3 object
  1042. */
  1043. Color3.prototype.toArray = function (array, index) {
  1044. if (index === undefined) {
  1045. index = 0;
  1046. }
  1047. array[index] = this.r;
  1048. array[index + 1] = this.g;
  1049. array[index + 2] = this.b;
  1050. return this;
  1051. };
  1052. /**
  1053. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1054. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1055. * @returns a new {BABYLON.Color4} object
  1056. */
  1057. Color3.prototype.toColor4 = function (alpha) {
  1058. if (alpha === void 0) { alpha = 1; }
  1059. return new Color4(this.r, this.g, this.b, alpha);
  1060. };
  1061. /**
  1062. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1063. * @returns the new array
  1064. */
  1065. Color3.prototype.asArray = function () {
  1066. var result = new Array();
  1067. this.toArray(result, 0);
  1068. return result;
  1069. };
  1070. /**
  1071. * Returns the luminance value
  1072. * @returns a float value
  1073. */
  1074. Color3.prototype.toLuminance = function () {
  1075. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1076. };
  1077. /**
  1078. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1079. * @param otherColor defines the second operand
  1080. * @returns the new Color3 object
  1081. */
  1082. Color3.prototype.multiply = function (otherColor) {
  1083. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1084. };
  1085. /**
  1086. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1087. * @param otherColor defines the second operand
  1088. * @param result defines the Color3 object where to store the result
  1089. * @returns the current Color3
  1090. */
  1091. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1092. result.r = this.r * otherColor.r;
  1093. result.g = this.g * otherColor.g;
  1094. result.b = this.b * otherColor.b;
  1095. return this;
  1096. };
  1097. /**
  1098. * Determines equality between Color3 objects
  1099. * @param otherColor defines the second operand
  1100. * @returns true if the rgb values are equal to the passed ones
  1101. */
  1102. Color3.prototype.equals = function (otherColor) {
  1103. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1104. };
  1105. /**
  1106. * Determines equality between the current Color3 object and a set of r,b,g values
  1107. * @param r defines the red component to check
  1108. * @param g defines the green component to check
  1109. * @param b defines the blue component to check
  1110. * @returns true if the rgb values are equal to the passed ones
  1111. */
  1112. Color3.prototype.equalsFloats = function (r, g, b) {
  1113. return this.r === r && this.g === g && this.b === b;
  1114. };
  1115. /**
  1116. * Multiplies in place each rgb value by scale
  1117. * @param scale defines the scaling factor
  1118. * @returns the updated Color3.
  1119. */
  1120. Color3.prototype.scale = function (scale) {
  1121. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1122. };
  1123. /**
  1124. * Multiplies the rgb values by scale and stores the result into "result"
  1125. * @param scale defines the scaling factor
  1126. * @param result defines the Color3 object where to store the result
  1127. * @returns the unmodified current Color3.
  1128. */
  1129. Color3.prototype.scaleToRef = function (scale, result) {
  1130. result.r = this.r * scale;
  1131. result.g = this.g * scale;
  1132. result.b = this.b * scale;
  1133. return this;
  1134. };
  1135. /**
  1136. * Clamps the rgb values by the min and max values and stores the result into "result"
  1137. * @param min defines minimum clamping value (default is 0)
  1138. * @param max defines maximum clamping value (default is 1)
  1139. * @param result defines color to store the result into
  1140. * @returns the original Color3
  1141. */
  1142. Color3.prototype.clampToRef = function (min, max, result) {
  1143. if (min === void 0) { min = 0; }
  1144. if (max === void 0) { max = 1; }
  1145. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1146. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1147. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1148. return this;
  1149. };
  1150. /**
  1151. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1152. * @param otherColor defines the second operand
  1153. * @returns the new Color3
  1154. */
  1155. Color3.prototype.add = function (otherColor) {
  1156. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1157. };
  1158. /**
  1159. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1160. * @param otherColor defines the second operand
  1161. * @param result defines Color3 object to store the result into
  1162. * @returns the unmodified current Color3
  1163. */
  1164. Color3.prototype.addToRef = function (otherColor, result) {
  1165. result.r = this.r + otherColor.r;
  1166. result.g = this.g + otherColor.g;
  1167. result.b = this.b + otherColor.b;
  1168. return this;
  1169. };
  1170. /**
  1171. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1172. * @param otherColor defines the second operand
  1173. * @returns the new Color3
  1174. */
  1175. Color3.prototype.subtract = function (otherColor) {
  1176. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1177. };
  1178. /**
  1179. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1180. * @param otherColor defines the second operand
  1181. * @param result defines Color3 object to store the result into
  1182. * @returns the unmodified current Color3
  1183. */
  1184. Color3.prototype.subtractToRef = function (otherColor, result) {
  1185. result.r = this.r - otherColor.r;
  1186. result.g = this.g - otherColor.g;
  1187. result.b = this.b - otherColor.b;
  1188. return this;
  1189. };
  1190. /**
  1191. * Copy the current object
  1192. * @returns a new Color3 copied the current one
  1193. */
  1194. Color3.prototype.clone = function () {
  1195. return new Color3(this.r, this.g, this.b);
  1196. };
  1197. /**
  1198. * Copies the rgb values from the source in the current Color3
  1199. * @param source defines the source Color3 object
  1200. * @returns the updated Color3 object
  1201. */
  1202. Color3.prototype.copyFrom = function (source) {
  1203. this.r = source.r;
  1204. this.g = source.g;
  1205. this.b = source.b;
  1206. return this;
  1207. };
  1208. /**
  1209. * Updates the Color3 rgb values from the passed floats
  1210. * @param r defines the red component to read from
  1211. * @param g defines the green component to read from
  1212. * @param b defines the blue component to read from
  1213. * @returns the current Color3 object
  1214. */
  1215. Color3.prototype.copyFromFloats = function (r, g, b) {
  1216. this.r = r;
  1217. this.g = g;
  1218. this.b = b;
  1219. return this;
  1220. };
  1221. /**
  1222. * Updates the Color3 rgb values from the passed floats
  1223. * @param r defines the red component to read from
  1224. * @param g defines the green component to read from
  1225. * @param b defines the blue component to read from
  1226. * @returns the current Color3 object
  1227. */
  1228. Color3.prototype.set = function (r, g, b) {
  1229. return this.copyFromFloats(r, g, b);
  1230. };
  1231. /**
  1232. * Compute the Color3 hexadecimal code as a string
  1233. * @returns a string containing the hexadecimal representation of the Color3 object
  1234. */
  1235. Color3.prototype.toHexString = function () {
  1236. var intR = (this.r * 255) | 0;
  1237. var intG = (this.g * 255) | 0;
  1238. var intB = (this.b * 255) | 0;
  1239. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1240. };
  1241. /**
  1242. * Computes a new Color3 converted from the current one to linear space
  1243. * @returns a new Color3 object
  1244. */
  1245. Color3.prototype.toLinearSpace = function () {
  1246. var convertedColor = new Color3();
  1247. this.toLinearSpaceToRef(convertedColor);
  1248. return convertedColor;
  1249. };
  1250. /**
  1251. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1252. * @param convertedColor defines the Color3 object where to store the linear space version
  1253. * @returns the unmodified Color3
  1254. */
  1255. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1256. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1257. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1258. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1259. return this;
  1260. };
  1261. /**
  1262. * Computes a new Color3 converted from the current one to gamma space
  1263. * @returns a new Color3 object
  1264. */
  1265. Color3.prototype.toGammaSpace = function () {
  1266. var convertedColor = new Color3();
  1267. this.toGammaSpaceToRef(convertedColor);
  1268. return convertedColor;
  1269. };
  1270. /**
  1271. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1272. * @param convertedColor defines the Color3 object where to store the gamma space version
  1273. * @returns the unmodified Color3
  1274. */
  1275. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1276. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1277. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1278. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1279. return this;
  1280. };
  1281. // Statics
  1282. /**
  1283. * Creates a new Color3 from the string containing valid hexadecimal values
  1284. * @param hex defines a string containing valid hexadecimal values
  1285. * @returns a new Color3 object
  1286. */
  1287. Color3.FromHexString = function (hex) {
  1288. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1289. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1290. return new Color3(0, 0, 0);
  1291. }
  1292. var r = parseInt(hex.substring(1, 3), 16);
  1293. var g = parseInt(hex.substring(3, 5), 16);
  1294. var b = parseInt(hex.substring(5, 7), 16);
  1295. return Color3.FromInts(r, g, b);
  1296. };
  1297. /**
  1298. * Creates a new Vector3 from the starting index of the passed array
  1299. * @param array defines the source array
  1300. * @param offset defines an offset in the source array
  1301. * @returns a new Color3 object
  1302. */
  1303. Color3.FromArray = function (array, offset) {
  1304. if (offset === void 0) { offset = 0; }
  1305. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1306. };
  1307. /**
  1308. * Creates a new Color3 from integer values (< 256)
  1309. * @param r defines the red component to read from (value between 0 and 255)
  1310. * @param g defines the green component to read from (value between 0 and 255)
  1311. * @param b defines the blue component to read from (value between 0 and 255)
  1312. * @returns a new Color3 object
  1313. */
  1314. Color3.FromInts = function (r, g, b) {
  1315. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1316. };
  1317. /**
  1318. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1319. * @param start defines the start Color3 value
  1320. * @param end defines the end Color3 value
  1321. * @param amount defines the gradient value between start and end
  1322. * @returns a new Color3 object
  1323. */
  1324. Color3.Lerp = function (start, end, amount) {
  1325. var r = start.r + ((end.r - start.r) * amount);
  1326. var g = start.g + ((end.g - start.g) * amount);
  1327. var b = start.b + ((end.b - start.b) * amount);
  1328. return new Color3(r, g, b);
  1329. };
  1330. /**
  1331. * Returns a Color3 value containing a red color
  1332. * @returns a new Color3 object
  1333. */
  1334. Color3.Red = function () { return new Color3(1, 0, 0); };
  1335. /**
  1336. * Returns a Color3 value containing a green color
  1337. * @returns a new Color3 object
  1338. */
  1339. Color3.Green = function () { return new Color3(0, 1, 0); };
  1340. /**
  1341. * Returns a Color3 value containing a blue color
  1342. * @returns a new Color3 object
  1343. */
  1344. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1345. /**
  1346. * Returns a Color3 value containing a black color
  1347. * @returns a new Color3 object
  1348. */
  1349. Color3.Black = function () { return new Color3(0, 0, 0); };
  1350. /**
  1351. * Returns a Color3 value containing a white color
  1352. * @returns a new Color3 object
  1353. */
  1354. Color3.White = function () { return new Color3(1, 1, 1); };
  1355. /**
  1356. * Returns a Color3 value containing a purple color
  1357. * @returns a new Color3 object
  1358. */
  1359. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1360. /**
  1361. * Returns a Color3 value containing a magenta color
  1362. * @returns a new Color3 object
  1363. */
  1364. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1365. /**
  1366. * Returns a Color3 value containing a yellow color
  1367. * @returns a new Color3 object
  1368. */
  1369. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1370. /**
  1371. * Returns a Color3 value containing a gray color
  1372. * @returns a new Color3 object
  1373. */
  1374. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1375. /**
  1376. * Returns a Color3 value containing a teal color
  1377. * @returns a new Color3 object
  1378. */
  1379. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1380. /**
  1381. * Returns a Color3 value containing a random color
  1382. * @returns a new Color3 object
  1383. */
  1384. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1385. return Color3;
  1386. }());
  1387. BABYLON.Color3 = Color3;
  1388. /**
  1389. * Class used to hold a RBGA color
  1390. */
  1391. var Color4 = /** @class */ (function () {
  1392. /**
  1393. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1394. * @param r defines the red component (between 0 and 1, default is 0)
  1395. * @param g defines the green component (between 0 and 1, default is 0)
  1396. * @param b defines the blue component (between 0 and 1, default is 0)
  1397. * @param a defines the alpha component (between 0 and 1, default is 1)
  1398. */
  1399. function Color4(
  1400. /**
  1401. * Defines the red component (between 0 and 1, default is 0)
  1402. */
  1403. r,
  1404. /**
  1405. * Defines the green component (between 0 and 1, default is 0)
  1406. */
  1407. g,
  1408. /**
  1409. * Defines the blue component (between 0 and 1, default is 0)
  1410. */
  1411. b,
  1412. /**
  1413. * Defines the alpha component (between 0 and 1, default is 1)
  1414. */
  1415. a) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. if (a === void 0) { a = 1; }
  1420. this.r = r;
  1421. this.g = g;
  1422. this.b = b;
  1423. this.a = a;
  1424. }
  1425. // Operators
  1426. /**
  1427. * Adds in place the passed Color4 values to the current Color4 object
  1428. * @param right defines the second operand
  1429. * @returns the current updated Color4 object
  1430. */
  1431. Color4.prototype.addInPlace = function (right) {
  1432. this.r += right.r;
  1433. this.g += right.g;
  1434. this.b += right.b;
  1435. this.a += right.a;
  1436. return this;
  1437. };
  1438. /**
  1439. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1440. * @returns the new array
  1441. */
  1442. Color4.prototype.asArray = function () {
  1443. var result = new Array();
  1444. this.toArray(result, 0);
  1445. return result;
  1446. };
  1447. /**
  1448. * Stores from the starting index in the passed array the Color4 successive values
  1449. * @param array defines the array where to store the r,g,b components
  1450. * @param index defines an optional index in the target array to define where to start storing values
  1451. * @returns the current Color4 object
  1452. */
  1453. Color4.prototype.toArray = function (array, index) {
  1454. if (index === undefined) {
  1455. index = 0;
  1456. }
  1457. array[index] = this.r;
  1458. array[index + 1] = this.g;
  1459. array[index + 2] = this.b;
  1460. array[index + 3] = this.a;
  1461. return this;
  1462. };
  1463. /**
  1464. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1465. * @param right defines the second operand
  1466. * @returns a new Color4 object
  1467. */
  1468. Color4.prototype.add = function (right) {
  1469. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1470. };
  1471. /**
  1472. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1473. * @param right defines the second operand
  1474. * @returns a new Color4 object
  1475. */
  1476. Color4.prototype.subtract = function (right) {
  1477. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1478. };
  1479. /**
  1480. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1481. * @param right defines the second operand
  1482. * @param result defines the Color4 object where to store the result
  1483. * @returns the current Color4 object
  1484. */
  1485. Color4.prototype.subtractToRef = function (right, result) {
  1486. result.r = this.r - right.r;
  1487. result.g = this.g - right.g;
  1488. result.b = this.b - right.b;
  1489. result.a = this.a - right.a;
  1490. return this;
  1491. };
  1492. /**
  1493. * Creates a new Color4 with the current Color4 values multiplied by scale
  1494. * @param scale defines the scaling factor to apply
  1495. * @returns a new Color4 object
  1496. */
  1497. Color4.prototype.scale = function (scale) {
  1498. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1499. };
  1500. /**
  1501. * Multiplies the current Color4 values by scale and stores the result in "result"
  1502. * @param scale defines the scaling factor to apply
  1503. * @param result defines the Color4 object where to store the result
  1504. * @returns the current Color4.
  1505. */
  1506. Color4.prototype.scaleToRef = function (scale, result) {
  1507. result.r = this.r * scale;
  1508. result.g = this.g * scale;
  1509. result.b = this.b * scale;
  1510. result.a = this.a * scale;
  1511. return this;
  1512. };
  1513. /**
  1514. * Clamps the rgb values by the min and max values and stores the result into "result"
  1515. * @param min defines minimum clamping value (default is 0)
  1516. * @param max defines maximum clamping value (default is 1)
  1517. * @param result defines color to store the result into.
  1518. * @returns the cuurent Color4
  1519. */
  1520. Color4.prototype.clampToRef = function (min, max, result) {
  1521. if (min === void 0) { min = 0; }
  1522. if (max === void 0) { max = 1; }
  1523. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1524. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1525. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1526. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1527. return this;
  1528. };
  1529. /**
  1530. * Multipy an Color4 value by another and return a new Color4 object
  1531. * @param color defines the Color4 value to multiply by
  1532. * @returns a new Color4 object
  1533. */
  1534. Color4.prototype.multiply = function (color) {
  1535. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1536. };
  1537. /**
  1538. * Multipy a Color4 value by another and push the result in a reference value
  1539. * @param color defines the Color4 value to multiply by
  1540. * @param result defines the Color4 to fill the result in
  1541. * @returns the result Color4
  1542. */
  1543. Color4.prototype.multiplyToRef = function (color, result) {
  1544. result.r = this.r * color.r;
  1545. result.g = this.g * color.g;
  1546. result.b = this.b * color.b;
  1547. result.a = this.a * color.a;
  1548. return result;
  1549. };
  1550. /**
  1551. * Creates a string with the Color4 current values
  1552. * @returns the string representation of the Color4 object
  1553. */
  1554. Color4.prototype.toString = function () {
  1555. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1556. };
  1557. /**
  1558. * Returns the string "Color4"
  1559. * @returns "Color4"
  1560. */
  1561. Color4.prototype.getClassName = function () {
  1562. return "Color4";
  1563. };
  1564. /**
  1565. * Compute the Color4 hash code
  1566. * @returns an unique number that can be used to hash Color4 objects
  1567. */
  1568. Color4.prototype.getHashCode = function () {
  1569. var hash = this.r || 0;
  1570. hash = (hash * 397) ^ (this.g || 0);
  1571. hash = (hash * 397) ^ (this.b || 0);
  1572. hash = (hash * 397) ^ (this.a || 0);
  1573. return hash;
  1574. };
  1575. /**
  1576. * Creates a new Color4 copied from the current one
  1577. * @returns a new Color4 object
  1578. */
  1579. Color4.prototype.clone = function () {
  1580. return new Color4(this.r, this.g, this.b, this.a);
  1581. };
  1582. /**
  1583. * Copies the passed Color4 values into the current one
  1584. * @param source defines the source Color4 object
  1585. * @returns the current updated Color4 object
  1586. */
  1587. Color4.prototype.copyFrom = function (source) {
  1588. this.r = source.r;
  1589. this.g = source.g;
  1590. this.b = source.b;
  1591. this.a = source.a;
  1592. return this;
  1593. };
  1594. /**
  1595. * Copies the passed float values into the current one
  1596. * @param r defines the red component to read from
  1597. * @param g defines the green component to read from
  1598. * @param b defines the blue component to read from
  1599. * @param a defines the alpha component to read from
  1600. * @returns the current updated Color4 object
  1601. */
  1602. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1603. this.r = r;
  1604. this.g = g;
  1605. this.b = b;
  1606. this.a = a;
  1607. return this;
  1608. };
  1609. /**
  1610. * Copies the passed float values into the current one
  1611. * @param r defines the red component to read from
  1612. * @param g defines the green component to read from
  1613. * @param b defines the blue component to read from
  1614. * @param a defines the alpha component to read from
  1615. * @returns the current updated Color4 object
  1616. */
  1617. Color4.prototype.set = function (r, g, b, a) {
  1618. return this.copyFromFloats(r, g, b, a);
  1619. };
  1620. /**
  1621. * Compute the Color4 hexadecimal code as a string
  1622. * @returns a string containing the hexadecimal representation of the Color4 object
  1623. */
  1624. Color4.prototype.toHexString = function () {
  1625. var intR = (this.r * 255) | 0;
  1626. var intG = (this.g * 255) | 0;
  1627. var intB = (this.b * 255) | 0;
  1628. var intA = (this.a * 255) | 0;
  1629. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1630. };
  1631. /**
  1632. * Computes a new Color4 converted from the current one to linear space
  1633. * @returns a new Color4 object
  1634. */
  1635. Color4.prototype.toLinearSpace = function () {
  1636. var convertedColor = new Color4();
  1637. this.toLinearSpaceToRef(convertedColor);
  1638. return convertedColor;
  1639. };
  1640. /**
  1641. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1642. * @param convertedColor defines the Color4 object where to store the linear space version
  1643. * @returns the unmodified Color4
  1644. */
  1645. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1646. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1647. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1648. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1649. convertedColor.a = this.a;
  1650. return this;
  1651. };
  1652. /**
  1653. * Computes a new Color4 converted from the current one to gamma space
  1654. * @returns a new Color4 object
  1655. */
  1656. Color4.prototype.toGammaSpace = function () {
  1657. var convertedColor = new Color4();
  1658. this.toGammaSpaceToRef(convertedColor);
  1659. return convertedColor;
  1660. };
  1661. /**
  1662. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  1663. * @param convertedColor defines the Color4 object where to store the gamma space version
  1664. * @returns the unmodified Color4
  1665. */
  1666. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1667. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1668. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1669. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1670. convertedColor.a = this.a;
  1671. return this;
  1672. };
  1673. // Statics
  1674. /**
  1675. * Creates a new Color4 from the string containing valid hexadecimal values
  1676. * @param hex defines a string containing valid hexadecimal values
  1677. * @returns a new Color4 object
  1678. */
  1679. Color4.FromHexString = function (hex) {
  1680. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1681. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1682. return new Color4(0.0, 0.0, 0.0, 0.0);
  1683. }
  1684. var r = parseInt(hex.substring(1, 3), 16);
  1685. var g = parseInt(hex.substring(3, 5), 16);
  1686. var b = parseInt(hex.substring(5, 7), 16);
  1687. var a = parseInt(hex.substring(7, 9), 16);
  1688. return Color4.FromInts(r, g, b, a);
  1689. };
  1690. /**
  1691. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1692. * @param left defines the start value
  1693. * @param right defines the end value
  1694. * @param amount defines the gradient factor
  1695. * @returns a new Color4 object
  1696. */
  1697. Color4.Lerp = function (left, right, amount) {
  1698. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1699. Color4.LerpToRef(left, right, amount, result);
  1700. return result;
  1701. };
  1702. /**
  1703. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1704. * @param left defines the start value
  1705. * @param right defines the end value
  1706. * @param amount defines the gradient factor
  1707. * @param result defines the Color4 object where to store data
  1708. */
  1709. Color4.LerpToRef = function (left, right, amount, result) {
  1710. result.r = left.r + (right.r - left.r) * amount;
  1711. result.g = left.g + (right.g - left.g) * amount;
  1712. result.b = left.b + (right.b - left.b) * amount;
  1713. result.a = left.a + (right.a - left.a) * amount;
  1714. };
  1715. /**
  1716. * Creates a new Color4 from the starting index element of the passed array
  1717. * @param array defines the source array to read from
  1718. * @param offset defines the offset in the source array
  1719. * @returns a new Color4 object
  1720. */
  1721. Color4.FromArray = function (array, offset) {
  1722. if (offset === void 0) { offset = 0; }
  1723. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1724. };
  1725. /**
  1726. * Creates a new Color3 from integer values (< 256)
  1727. * @param r defines the red component to read from (value between 0 and 255)
  1728. * @param g defines the green component to read from (value between 0 and 255)
  1729. * @param b defines the blue component to read from (value between 0 and 255)
  1730. * @param a defines the alpha component to read from (value between 0 and 255)
  1731. * @returns a new Color3 object
  1732. */
  1733. Color4.FromInts = function (r, g, b, a) {
  1734. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1735. };
  1736. /**
  1737. * Check the content of a given array and convert it to an array containing RGBA data
  1738. * If the original array was already containing count * 4 values then it is returned directly
  1739. * @param colors defines the array to check
  1740. * @param count defines the number of RGBA data to expect
  1741. * @returns an array containing count * 4 values (RGBA)
  1742. */
  1743. Color4.CheckColors4 = function (colors, count) {
  1744. // Check if color3 was used
  1745. if (colors.length === count * 3) {
  1746. var colors4 = [];
  1747. for (var index = 0; index < colors.length; index += 3) {
  1748. var newIndex = (index / 3) * 4;
  1749. colors4[newIndex] = colors[index];
  1750. colors4[newIndex + 1] = colors[index + 1];
  1751. colors4[newIndex + 2] = colors[index + 2];
  1752. colors4[newIndex + 3] = 1.0;
  1753. }
  1754. return colors4;
  1755. }
  1756. return colors;
  1757. };
  1758. return Color4;
  1759. }());
  1760. BABYLON.Color4 = Color4;
  1761. var Vector2 = /** @class */ (function () {
  1762. /**
  1763. * Creates a new Vector2 from the passed x and y coordinates.
  1764. */
  1765. function Vector2(x, y) {
  1766. this.x = x;
  1767. this.y = y;
  1768. }
  1769. /**
  1770. * Returns a string with the Vector2 coordinates.
  1771. */
  1772. Vector2.prototype.toString = function () {
  1773. return "{X: " + this.x + " Y:" + this.y + "}";
  1774. };
  1775. /**
  1776. * Returns the string "Vector2"
  1777. */
  1778. Vector2.prototype.getClassName = function () {
  1779. return "Vector2";
  1780. };
  1781. /**
  1782. * Returns the Vector2 hash code as a number.
  1783. */
  1784. Vector2.prototype.getHashCode = function () {
  1785. var hash = this.x || 0;
  1786. hash = (hash * 397) ^ (this.y || 0);
  1787. return hash;
  1788. };
  1789. // Operators
  1790. /**
  1791. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1792. * Returns the Vector2.
  1793. */
  1794. Vector2.prototype.toArray = function (array, index) {
  1795. if (index === void 0) { index = 0; }
  1796. array[index] = this.x;
  1797. array[index + 1] = this.y;
  1798. return this;
  1799. };
  1800. /**
  1801. * Returns a new array with 2 elements : the Vector2 coordinates.
  1802. */
  1803. Vector2.prototype.asArray = function () {
  1804. var result = new Array();
  1805. this.toArray(result, 0);
  1806. return result;
  1807. };
  1808. /**
  1809. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1810. * Returns the updated Vector2.
  1811. */
  1812. Vector2.prototype.copyFrom = function (source) {
  1813. this.x = source.x;
  1814. this.y = source.y;
  1815. return this;
  1816. };
  1817. /**
  1818. * Sets the Vector2 coordinates with the passed floats.
  1819. * Returns the updated Vector2.
  1820. */
  1821. Vector2.prototype.copyFromFloats = function (x, y) {
  1822. this.x = x;
  1823. this.y = y;
  1824. return this;
  1825. };
  1826. /**
  1827. * Sets the Vector2 coordinates with the passed floats.
  1828. * Returns the updated Vector2.
  1829. */
  1830. Vector2.prototype.set = function (x, y) {
  1831. return this.copyFromFloats(x, y);
  1832. };
  1833. /**
  1834. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1835. */
  1836. Vector2.prototype.add = function (otherVector) {
  1837. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1838. };
  1839. /**
  1840. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1841. * Returns the Vector2.
  1842. */
  1843. Vector2.prototype.addToRef = function (otherVector, result) {
  1844. result.x = this.x + otherVector.x;
  1845. result.y = this.y + otherVector.y;
  1846. return this;
  1847. };
  1848. /**
  1849. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1850. * Returns the updated Vector2.
  1851. */
  1852. Vector2.prototype.addInPlace = function (otherVector) {
  1853. this.x += otherVector.x;
  1854. this.y += otherVector.y;
  1855. return this;
  1856. };
  1857. /**
  1858. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1859. */
  1860. Vector2.prototype.addVector3 = function (otherVector) {
  1861. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1862. };
  1863. /**
  1864. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1865. */
  1866. Vector2.prototype.subtract = function (otherVector) {
  1867. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1868. };
  1869. /**
  1870. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1871. * Returns the Vector2.
  1872. */
  1873. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1874. result.x = this.x - otherVector.x;
  1875. result.y = this.y - otherVector.y;
  1876. return this;
  1877. };
  1878. /**
  1879. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1880. * Returns the updated Vector2.
  1881. */
  1882. Vector2.prototype.subtractInPlace = function (otherVector) {
  1883. this.x -= otherVector.x;
  1884. this.y -= otherVector.y;
  1885. return this;
  1886. };
  1887. /**
  1888. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1889. * Returns the updated Vector2.
  1890. */
  1891. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1892. this.x *= otherVector.x;
  1893. this.y *= otherVector.y;
  1894. return this;
  1895. };
  1896. /**
  1897. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1898. */
  1899. Vector2.prototype.multiply = function (otherVector) {
  1900. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1901. };
  1902. /**
  1903. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1904. * Returns the Vector2.
  1905. */
  1906. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1907. result.x = this.x * otherVector.x;
  1908. result.y = this.y * otherVector.y;
  1909. return this;
  1910. };
  1911. /**
  1912. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1913. */
  1914. Vector2.prototype.multiplyByFloats = function (x, y) {
  1915. return new Vector2(this.x * x, this.y * y);
  1916. };
  1917. /**
  1918. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1919. */
  1920. Vector2.prototype.divide = function (otherVector) {
  1921. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1922. };
  1923. /**
  1924. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1925. * Returns the Vector2.
  1926. */
  1927. Vector2.prototype.divideToRef = function (otherVector, result) {
  1928. result.x = this.x / otherVector.x;
  1929. result.y = this.y / otherVector.y;
  1930. return this;
  1931. };
  1932. /**
  1933. * Divides the current Vector3 coordinates by the passed ones.
  1934. * Returns the updated Vector3.
  1935. */
  1936. Vector2.prototype.divideInPlace = function (otherVector) {
  1937. return this.divideToRef(otherVector, this);
  1938. };
  1939. /**
  1940. * Returns a new Vector2 with current Vector2 negated coordinates.
  1941. */
  1942. Vector2.prototype.negate = function () {
  1943. return new Vector2(-this.x, -this.y);
  1944. };
  1945. /**
  1946. * Multiply the Vector2 coordinates by scale.
  1947. * Returns the updated Vector2.
  1948. */
  1949. Vector2.prototype.scaleInPlace = function (scale) {
  1950. this.x *= scale;
  1951. this.y *= scale;
  1952. return this;
  1953. };
  1954. /**
  1955. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1956. */
  1957. Vector2.prototype.scale = function (scale) {
  1958. return new Vector2(this.x * scale, this.y * scale);
  1959. };
  1960. /**
  1961. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1962. */
  1963. Vector2.prototype.equals = function (otherVector) {
  1964. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1965. };
  1966. /**
  1967. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1968. */
  1969. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1970. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1971. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1972. };
  1973. // Properties
  1974. /**
  1975. * Returns the vector length (float).
  1976. */
  1977. Vector2.prototype.length = function () {
  1978. return Math.sqrt(this.x * this.x + this.y * this.y);
  1979. };
  1980. /**
  1981. * Returns the vector squared length (float);
  1982. */
  1983. Vector2.prototype.lengthSquared = function () {
  1984. return (this.x * this.x + this.y * this.y);
  1985. };
  1986. // Methods
  1987. /**
  1988. * Normalize the vector.
  1989. * Returns the updated Vector2.
  1990. */
  1991. Vector2.prototype.normalize = function () {
  1992. var len = this.length();
  1993. if (len === 0)
  1994. return this;
  1995. var num = 1.0 / len;
  1996. this.x *= num;
  1997. this.y *= num;
  1998. return this;
  1999. };
  2000. /**
  2001. * Returns a new Vector2 copied from the Vector2.
  2002. */
  2003. Vector2.prototype.clone = function () {
  2004. return new Vector2(this.x, this.y);
  2005. };
  2006. // Statics
  2007. /**
  2008. * Returns a new Vector2(0, 0)
  2009. */
  2010. Vector2.Zero = function () {
  2011. return new Vector2(0, 0);
  2012. };
  2013. /**
  2014. * Returns a new Vector2(1, 1)
  2015. */
  2016. Vector2.One = function () {
  2017. return new Vector2(1, 1);
  2018. };
  2019. /**
  2020. * Returns a new Vector2 set from the passed index element of the passed array.
  2021. */
  2022. Vector2.FromArray = function (array, offset) {
  2023. if (offset === void 0) { offset = 0; }
  2024. return new Vector2(array[offset], array[offset + 1]);
  2025. };
  2026. /**
  2027. * Sets "result" from the passed index element of the passed array.
  2028. */
  2029. Vector2.FromArrayToRef = function (array, offset, result) {
  2030. result.x = array[offset];
  2031. result.y = array[offset + 1];
  2032. };
  2033. /**
  2034. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2035. */
  2036. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2037. var squared = amount * amount;
  2038. var cubed = amount * squared;
  2039. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2040. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2041. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2042. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2043. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2044. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2045. return new Vector2(x, y);
  2046. };
  2047. /**
  2048. * 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".
  2049. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2050. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2051. */
  2052. Vector2.Clamp = function (value, min, max) {
  2053. var x = value.x;
  2054. x = (x > max.x) ? max.x : x;
  2055. x = (x < min.x) ? min.x : x;
  2056. var y = value.y;
  2057. y = (y > max.y) ? max.y : y;
  2058. y = (y < min.y) ? min.y : y;
  2059. return new Vector2(x, y);
  2060. };
  2061. /**
  2062. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2063. */
  2064. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2065. var squared = amount * amount;
  2066. var cubed = amount * squared;
  2067. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2068. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2069. var part3 = (cubed - (2.0 * squared)) + amount;
  2070. var part4 = cubed - squared;
  2071. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2072. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2073. return new Vector2(x, y);
  2074. };
  2075. /**
  2076. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2077. */
  2078. Vector2.Lerp = function (start, end, amount) {
  2079. var x = start.x + ((end.x - start.x) * amount);
  2080. var y = start.y + ((end.y - start.y) * amount);
  2081. return new Vector2(x, y);
  2082. };
  2083. /**
  2084. * Returns the dot product (float) of the vector "left" and the vector "right".
  2085. */
  2086. Vector2.Dot = function (left, right) {
  2087. return left.x * right.x + left.y * right.y;
  2088. };
  2089. /**
  2090. * Returns a new Vector2 equal to the normalized passed vector.
  2091. */
  2092. Vector2.Normalize = function (vector) {
  2093. var newVector = vector.clone();
  2094. newVector.normalize();
  2095. return newVector;
  2096. };
  2097. /**
  2098. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2099. */
  2100. Vector2.Minimize = function (left, right) {
  2101. var x = (left.x < right.x) ? left.x : right.x;
  2102. var y = (left.y < right.y) ? left.y : right.y;
  2103. return new Vector2(x, y);
  2104. };
  2105. /**
  2106. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2107. */
  2108. Vector2.Maximize = function (left, right) {
  2109. var x = (left.x > right.x) ? left.x : right.x;
  2110. var y = (left.y > right.y) ? left.y : right.y;
  2111. return new Vector2(x, y);
  2112. };
  2113. /**
  2114. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2115. */
  2116. Vector2.Transform = function (vector, transformation) {
  2117. var r = Vector2.Zero();
  2118. Vector2.TransformToRef(vector, transformation, r);
  2119. return r;
  2120. };
  2121. /**
  2122. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2123. */
  2124. Vector2.TransformToRef = function (vector, transformation, result) {
  2125. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2126. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2127. result.x = x;
  2128. result.y = y;
  2129. };
  2130. /**
  2131. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2132. */
  2133. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2134. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2135. var sign = a < 0 ? -1 : 1;
  2136. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2137. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2138. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2139. };
  2140. /**
  2141. * Returns the distance (float) between the vectors "value1" and "value2".
  2142. */
  2143. Vector2.Distance = function (value1, value2) {
  2144. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2145. };
  2146. /**
  2147. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2148. */
  2149. Vector2.DistanceSquared = function (value1, value2) {
  2150. var x = value1.x - value2.x;
  2151. var y = value1.y - value2.y;
  2152. return (x * x) + (y * y);
  2153. };
  2154. /**
  2155. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2156. */
  2157. Vector2.Center = function (value1, value2) {
  2158. var center = value1.add(value2);
  2159. center.scaleInPlace(0.5);
  2160. return center;
  2161. };
  2162. /**
  2163. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2164. */
  2165. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2166. var l2 = Vector2.DistanceSquared(segA, segB);
  2167. if (l2 === 0.0) {
  2168. return Vector2.Distance(p, segA);
  2169. }
  2170. var v = segB.subtract(segA);
  2171. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2172. var proj = segA.add(v.multiplyByFloats(t, t));
  2173. return Vector2.Distance(p, proj);
  2174. };
  2175. return Vector2;
  2176. }());
  2177. BABYLON.Vector2 = Vector2;
  2178. var Vector3 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2181. * A Vector3 is the main object used in 3D geometry.
  2182. * It can represent etiher the coordinates of a point the space, either a direction.
  2183. */
  2184. function Vector3(x, y, z) {
  2185. this.x = x;
  2186. this.y = y;
  2187. this.z = z;
  2188. }
  2189. /**
  2190. * Returns a string with the Vector3 coordinates.
  2191. */
  2192. Vector3.prototype.toString = function () {
  2193. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2194. };
  2195. /**
  2196. * Returns the string "Vector3"
  2197. */
  2198. Vector3.prototype.getClassName = function () {
  2199. return "Vector3";
  2200. };
  2201. /**
  2202. * Returns the Vector hash code.
  2203. */
  2204. Vector3.prototype.getHashCode = function () {
  2205. var hash = this.x || 0;
  2206. hash = (hash * 397) ^ (this.y || 0);
  2207. hash = (hash * 397) ^ (this.z || 0);
  2208. return hash;
  2209. };
  2210. // Operators
  2211. /**
  2212. * Returns a new array with three elements : the coordinates the Vector3.
  2213. */
  2214. Vector3.prototype.asArray = function () {
  2215. var result = [];
  2216. this.toArray(result, 0);
  2217. return result;
  2218. };
  2219. /**
  2220. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2221. * Returns the Vector3.
  2222. */
  2223. Vector3.prototype.toArray = function (array, index) {
  2224. if (index === void 0) { index = 0; }
  2225. array[index] = this.x;
  2226. array[index + 1] = this.y;
  2227. array[index + 2] = this.z;
  2228. return this;
  2229. };
  2230. /**
  2231. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2232. */
  2233. Vector3.prototype.toQuaternion = function () {
  2234. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2235. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2236. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2237. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2238. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2239. var cosy = Math.cos(this.y * 0.5);
  2240. var siny = Math.sin(this.y * 0.5);
  2241. result.x = coszMinusx * siny;
  2242. result.y = -sinzMinusx * siny;
  2243. result.z = sinxPlusz * cosy;
  2244. result.w = cosxPlusz * cosy;
  2245. return result;
  2246. };
  2247. /**
  2248. * Adds the passed vector to the current Vector3.
  2249. * Returns the updated Vector3.
  2250. */
  2251. Vector3.prototype.addInPlace = function (otherVector) {
  2252. this.x += otherVector.x;
  2253. this.y += otherVector.y;
  2254. this.z += otherVector.z;
  2255. return this;
  2256. };
  2257. /**
  2258. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2259. */
  2260. Vector3.prototype.add = function (otherVector) {
  2261. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2262. };
  2263. /**
  2264. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2265. * Returns the current Vector3.
  2266. */
  2267. Vector3.prototype.addToRef = function (otherVector, result) {
  2268. result.x = this.x + otherVector.x;
  2269. result.y = this.y + otherVector.y;
  2270. result.z = this.z + otherVector.z;
  2271. return this;
  2272. };
  2273. /**
  2274. * Subtract the passed vector from the current Vector3.
  2275. * Returns the updated Vector3.
  2276. */
  2277. Vector3.prototype.subtractInPlace = function (otherVector) {
  2278. this.x -= otherVector.x;
  2279. this.y -= otherVector.y;
  2280. this.z -= otherVector.z;
  2281. return this;
  2282. };
  2283. /**
  2284. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2285. */
  2286. Vector3.prototype.subtract = function (otherVector) {
  2287. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2288. };
  2289. /**
  2290. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2291. * Returns the current Vector3.
  2292. */
  2293. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2294. result.x = this.x - otherVector.x;
  2295. result.y = this.y - otherVector.y;
  2296. result.z = this.z - otherVector.z;
  2297. return this;
  2298. };
  2299. /**
  2300. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2301. */
  2302. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2303. return new Vector3(this.x - x, this.y - y, this.z - z);
  2304. };
  2305. /**
  2306. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2307. * Returns the current Vector3.
  2308. */
  2309. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2310. result.x = this.x - x;
  2311. result.y = this.y - y;
  2312. result.z = this.z - z;
  2313. return this;
  2314. };
  2315. /**
  2316. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2317. */
  2318. Vector3.prototype.negate = function () {
  2319. return new Vector3(-this.x, -this.y, -this.z);
  2320. };
  2321. /**
  2322. * Multiplies the Vector3 coordinates by the float "scale".
  2323. * Returns the updated Vector3.
  2324. */
  2325. Vector3.prototype.scaleInPlace = function (scale) {
  2326. this.x *= scale;
  2327. this.y *= scale;
  2328. this.z *= scale;
  2329. return this;
  2330. };
  2331. /**
  2332. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2333. */
  2334. Vector3.prototype.scale = function (scale) {
  2335. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2336. };
  2337. /**
  2338. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2339. * Returns the current Vector3.
  2340. */
  2341. Vector3.prototype.scaleToRef = function (scale, result) {
  2342. result.x = this.x * scale;
  2343. result.y = this.y * scale;
  2344. result.z = this.z * scale;
  2345. return this;
  2346. };
  2347. /**
  2348. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2349. */
  2350. Vector3.prototype.equals = function (otherVector) {
  2351. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2352. };
  2353. /**
  2354. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2355. */
  2356. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2357. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2358. 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);
  2359. };
  2360. /**
  2361. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2362. */
  2363. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2364. return this.x === x && this.y === y && this.z === z;
  2365. };
  2366. /**
  2367. * Muliplies the current Vector3 coordinates by the passed ones.
  2368. * Returns the updated Vector3.
  2369. */
  2370. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2371. this.x *= otherVector.x;
  2372. this.y *= otherVector.y;
  2373. this.z *= otherVector.z;
  2374. return this;
  2375. };
  2376. /**
  2377. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2378. */
  2379. Vector3.prototype.multiply = function (otherVector) {
  2380. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2381. };
  2382. /**
  2383. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2384. * Returns the current Vector3.
  2385. */
  2386. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2387. result.x = this.x * otherVector.x;
  2388. result.y = this.y * otherVector.y;
  2389. result.z = this.z * otherVector.z;
  2390. return this;
  2391. };
  2392. /**
  2393. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2394. */
  2395. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2396. return new Vector3(this.x * x, this.y * y, this.z * z);
  2397. };
  2398. /**
  2399. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2400. */
  2401. Vector3.prototype.divide = function (otherVector) {
  2402. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2403. };
  2404. /**
  2405. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2406. * Returns the current Vector3.
  2407. */
  2408. Vector3.prototype.divideToRef = function (otherVector, result) {
  2409. result.x = this.x / otherVector.x;
  2410. result.y = this.y / otherVector.y;
  2411. result.z = this.z / otherVector.z;
  2412. return this;
  2413. };
  2414. /**
  2415. * Divides the current Vector3 coordinates by the passed ones.
  2416. * Returns the updated Vector3.
  2417. */
  2418. Vector3.prototype.divideInPlace = function (otherVector) {
  2419. return this.divideToRef(otherVector, this);
  2420. };
  2421. /**
  2422. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2423. * Returns the updated Vector3.
  2424. */
  2425. Vector3.prototype.MinimizeInPlace = function (other) {
  2426. if (other.x < this.x)
  2427. this.x = other.x;
  2428. if (other.y < this.y)
  2429. this.y = other.y;
  2430. if (other.z < this.z)
  2431. this.z = other.z;
  2432. return this;
  2433. };
  2434. /**
  2435. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2436. * Returns the updated Vector3.
  2437. */
  2438. Vector3.prototype.MaximizeInPlace = function (other) {
  2439. if (other.x > this.x)
  2440. this.x = other.x;
  2441. if (other.y > this.y)
  2442. this.y = other.y;
  2443. if (other.z > this.z)
  2444. this.z = other.z;
  2445. return this;
  2446. };
  2447. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2448. /**
  2449. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2450. */
  2451. get: function () {
  2452. var absX = Math.abs(this.x);
  2453. var absY = Math.abs(this.y);
  2454. if (absX !== absY) {
  2455. return true;
  2456. }
  2457. var absZ = Math.abs(this.z);
  2458. if (absX !== absZ) {
  2459. return true;
  2460. }
  2461. if (absY !== absZ) {
  2462. return true;
  2463. }
  2464. return false;
  2465. },
  2466. enumerable: true,
  2467. configurable: true
  2468. });
  2469. // Properties
  2470. /**
  2471. * Returns the length of the Vector3 (float).
  2472. */
  2473. Vector3.prototype.length = function () {
  2474. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2475. };
  2476. /**
  2477. * Returns the squared length of the Vector3 (float).
  2478. */
  2479. Vector3.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2481. };
  2482. /**
  2483. * Normalize the current Vector3.
  2484. * Returns the updated Vector3.
  2485. * /!\ In place operation.
  2486. */
  2487. Vector3.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0 || len === 1.0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. this.z *= num;
  2495. return this;
  2496. };
  2497. /**
  2498. * Normalize the current Vector3 to a new vector.
  2499. * @returns the new Vector3.
  2500. */
  2501. Vector3.prototype.normalizeToNew = function () {
  2502. var normalized = new Vector3(0, 0, 0);
  2503. this.normalizeToRef(normalized);
  2504. return normalized;
  2505. };
  2506. /**
  2507. * Normalize the current Vector3 to the reference.
  2508. * @param the reference to update.
  2509. * @returns the updated Vector3.
  2510. */
  2511. Vector3.prototype.normalizeToRef = function (reference) {
  2512. var len = this.length();
  2513. if (len === 0 || len === 1.0) {
  2514. reference.set(this.x, this.y, this.z);
  2515. return reference;
  2516. }
  2517. var scale = 1.0 / len;
  2518. this.scaleToRef(scale, reference);
  2519. return reference;
  2520. };
  2521. /**
  2522. * Returns a new Vector3 copied from the current Vector3.
  2523. */
  2524. Vector3.prototype.clone = function () {
  2525. return new Vector3(this.x, this.y, this.z);
  2526. };
  2527. /**
  2528. * Copies the passed vector coordinates to the current Vector3 ones.
  2529. * Returns the updated Vector3.
  2530. */
  2531. Vector3.prototype.copyFrom = function (source) {
  2532. this.x = source.x;
  2533. this.y = source.y;
  2534. this.z = source.z;
  2535. return this;
  2536. };
  2537. /**
  2538. * Copies the passed floats to the current Vector3 coordinates.
  2539. * Returns the updated Vector3.
  2540. */
  2541. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2542. this.x = x;
  2543. this.y = y;
  2544. this.z = z;
  2545. return this;
  2546. };
  2547. /**
  2548. * Copies the passed floats to the current Vector3 coordinates.
  2549. * Returns the updated Vector3.
  2550. */
  2551. Vector3.prototype.set = function (x, y, z) {
  2552. return this.copyFromFloats(x, y, z);
  2553. };
  2554. // Statics
  2555. /**
  2556. *
  2557. */
  2558. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2559. var d0 = Vector3.Dot(vector0, axis) - size;
  2560. var d1 = Vector3.Dot(vector1, axis) - size;
  2561. var s = d0 / (d0 - d1);
  2562. return s;
  2563. };
  2564. /**
  2565. * Get angle between two vectors.
  2566. * @param vector0 angle between vector0 and vector1
  2567. * @param vector1 angle between vector0 and vector1
  2568. * @param normal direction of the normal.
  2569. * @return the angle between vector0 and vector1.
  2570. */
  2571. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2572. var v0 = vector0.clone().normalize();
  2573. var v1 = vector1.clone().normalize();
  2574. var dot = Vector3.Dot(v0, v1);
  2575. var n = Vector3.Cross(v0, v1);
  2576. if (Vector3.Dot(n, normal) > 0) {
  2577. return Math.acos(dot);
  2578. }
  2579. return -Math.acos(dot);
  2580. };
  2581. /**
  2582. * Returns a new Vector3 set from the index "offset" of the passed array.
  2583. */
  2584. Vector3.FromArray = function (array, offset) {
  2585. if (!offset) {
  2586. offset = 0;
  2587. }
  2588. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2589. };
  2590. /**
  2591. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2592. * This function is deprecated. Use FromArray instead.
  2593. */
  2594. Vector3.FromFloatArray = function (array, offset) {
  2595. return Vector3.FromArray(array, offset);
  2596. };
  2597. /**
  2598. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2599. */
  2600. Vector3.FromArrayToRef = function (array, offset, result) {
  2601. result.x = array[offset];
  2602. result.y = array[offset + 1];
  2603. result.z = array[offset + 2];
  2604. };
  2605. /**
  2606. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2607. * This function is deprecated. Use FromArrayToRef instead.
  2608. */
  2609. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2610. return Vector3.FromArrayToRef(array, offset, result);
  2611. };
  2612. /**
  2613. * Sets the passed vector "result" with the passed floats.
  2614. */
  2615. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2616. result.x = x;
  2617. result.y = y;
  2618. result.z = z;
  2619. };
  2620. /**
  2621. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2622. */
  2623. Vector3.Zero = function () {
  2624. return new Vector3(0.0, 0.0, 0.0);
  2625. };
  2626. /**
  2627. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2628. */
  2629. Vector3.One = function () {
  2630. return new Vector3(1.0, 1.0, 1.0);
  2631. };
  2632. /**
  2633. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2634. */
  2635. Vector3.Up = function () {
  2636. return new Vector3(0.0, 1.0, 0.0);
  2637. };
  2638. /**
  2639. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2640. */
  2641. Vector3.Forward = function () {
  2642. return new Vector3(0.0, 0.0, 1.0);
  2643. };
  2644. /**
  2645. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2646. */
  2647. Vector3.Right = function () {
  2648. return new Vector3(1.0, 0.0, 0.0);
  2649. };
  2650. /**
  2651. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2652. */
  2653. Vector3.Left = function () {
  2654. return new Vector3(-1.0, 0.0, 0.0);
  2655. };
  2656. /**
  2657. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2658. * This method computes tranformed coordinates only, not transformed direction vectors.
  2659. */
  2660. Vector3.TransformCoordinates = function (vector, transformation) {
  2661. var result = Vector3.Zero();
  2662. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2663. return result;
  2664. };
  2665. /**
  2666. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2667. * This method computes tranformed coordinates only, not transformed direction vectors.
  2668. */
  2669. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2670. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2671. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2672. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2673. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2674. result.x = x / w;
  2675. result.y = y / w;
  2676. result.z = z / w;
  2677. };
  2678. /**
  2679. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2680. * This method computes tranformed coordinates only, not transformed direction vectors.
  2681. */
  2682. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2683. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2684. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2685. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2686. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2687. result.x = rx / rw;
  2688. result.y = ry / rw;
  2689. result.z = rz / rw;
  2690. };
  2691. /**
  2692. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2693. * This methods computes transformed normalized direction vectors only.
  2694. */
  2695. Vector3.TransformNormal = function (vector, transformation) {
  2696. var result = Vector3.Zero();
  2697. Vector3.TransformNormalToRef(vector, transformation, result);
  2698. return result;
  2699. };
  2700. /**
  2701. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2702. * This methods computes transformed normalized direction vectors only.
  2703. */
  2704. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2705. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2706. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2707. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2708. result.x = x;
  2709. result.y = y;
  2710. result.z = z;
  2711. };
  2712. /**
  2713. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2714. * This methods computes transformed normalized direction vectors only.
  2715. */
  2716. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2717. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2718. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2719. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2720. };
  2721. /**
  2722. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2723. */
  2724. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2725. var squared = amount * amount;
  2726. var cubed = amount * squared;
  2727. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2728. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2729. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2730. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2731. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2732. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2733. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2734. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2735. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2736. return new Vector3(x, y, z);
  2737. };
  2738. /**
  2739. * 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".
  2740. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2741. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2742. */
  2743. Vector3.Clamp = function (value, min, max) {
  2744. var x = value.x;
  2745. x = (x > max.x) ? max.x : x;
  2746. x = (x < min.x) ? min.x : x;
  2747. var y = value.y;
  2748. y = (y > max.y) ? max.y : y;
  2749. y = (y < min.y) ? min.y : y;
  2750. var z = value.z;
  2751. z = (z > max.z) ? max.z : z;
  2752. z = (z < min.z) ? min.z : z;
  2753. return new Vector3(x, y, z);
  2754. };
  2755. /**
  2756. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2757. */
  2758. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2759. var squared = amount * amount;
  2760. var cubed = amount * squared;
  2761. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2762. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2763. var part3 = (cubed - (2.0 * squared)) + amount;
  2764. var part4 = cubed - squared;
  2765. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2766. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2767. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2768. return new Vector3(x, y, z);
  2769. };
  2770. /**
  2771. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2772. */
  2773. Vector3.Lerp = function (start, end, amount) {
  2774. var result = new Vector3(0, 0, 0);
  2775. Vector3.LerpToRef(start, end, amount, result);
  2776. return result;
  2777. };
  2778. /**
  2779. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2780. */
  2781. Vector3.LerpToRef = function (start, end, amount, result) {
  2782. result.x = start.x + ((end.x - start.x) * amount);
  2783. result.y = start.y + ((end.y - start.y) * amount);
  2784. result.z = start.z + ((end.z - start.z) * amount);
  2785. };
  2786. /**
  2787. * Returns the dot product (float) between the vectors "left" and "right".
  2788. */
  2789. Vector3.Dot = function (left, right) {
  2790. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2791. };
  2792. /**
  2793. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2794. * The cross product is then orthogonal to both "left" and "right".
  2795. */
  2796. Vector3.Cross = function (left, right) {
  2797. var result = Vector3.Zero();
  2798. Vector3.CrossToRef(left, right, result);
  2799. return result;
  2800. };
  2801. /**
  2802. * Sets the passed vector "result" with the cross product of "left" and "right".
  2803. * The cross product is then orthogonal to both "left" and "right".
  2804. */
  2805. Vector3.CrossToRef = function (left, right, result) {
  2806. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2807. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2808. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2809. result.copyFrom(MathTmp.Vector3[0]);
  2810. };
  2811. /**
  2812. * Returns a new Vector3 as the normalization of the passed vector.
  2813. */
  2814. Vector3.Normalize = function (vector) {
  2815. var result = Vector3.Zero();
  2816. Vector3.NormalizeToRef(vector, result);
  2817. return result;
  2818. };
  2819. /**
  2820. * Sets the passed vector "result" with the normalization of the passed first vector.
  2821. */
  2822. Vector3.NormalizeToRef = function (vector, result) {
  2823. result.copyFrom(vector);
  2824. result.normalize();
  2825. };
  2826. Vector3.Project = function (vector, world, transform, viewport) {
  2827. var cw = viewport.width;
  2828. var ch = viewport.height;
  2829. var cx = viewport.x;
  2830. var cy = viewport.y;
  2831. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2832. 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);
  2833. var matrix = MathTmp.Matrix[0];
  2834. world.multiplyToRef(transform, matrix);
  2835. matrix.multiplyToRef(viewportMatrix, matrix);
  2836. return Vector3.TransformCoordinates(vector, matrix);
  2837. };
  2838. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2839. var matrix = MathTmp.Matrix[0];
  2840. world.multiplyToRef(transform, matrix);
  2841. matrix.invert();
  2842. source.x = source.x / viewportWidth * 2 - 1;
  2843. source.y = -(source.y / viewportHeight * 2 - 1);
  2844. var vector = Vector3.TransformCoordinates(source, matrix);
  2845. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2846. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2847. vector = vector.scale(1.0 / num);
  2848. }
  2849. return vector;
  2850. };
  2851. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2852. var result = Vector3.Zero();
  2853. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2854. return result;
  2855. };
  2856. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2857. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2858. };
  2859. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2860. var matrix = MathTmp.Matrix[0];
  2861. world.multiplyToRef(view, matrix);
  2862. matrix.multiplyToRef(projection, matrix);
  2863. matrix.invert();
  2864. var screenSource = MathTmp.Vector3[0];
  2865. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2866. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2867. screenSource.z = 2 * sourceZ - 1.0;
  2868. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2869. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2870. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2871. result.scaleInPlace(1.0 / num);
  2872. }
  2873. };
  2874. Vector3.Minimize = function (left, right) {
  2875. var min = left.clone();
  2876. min.MinimizeInPlace(right);
  2877. return min;
  2878. };
  2879. Vector3.Maximize = function (left, right) {
  2880. var max = left.clone();
  2881. max.MaximizeInPlace(right);
  2882. return max;
  2883. };
  2884. /**
  2885. * Returns the distance (float) between the vectors "value1" and "value2".
  2886. */
  2887. Vector3.Distance = function (value1, value2) {
  2888. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2889. };
  2890. /**
  2891. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2892. */
  2893. Vector3.DistanceSquared = function (value1, value2) {
  2894. var x = value1.x - value2.x;
  2895. var y = value1.y - value2.y;
  2896. var z = value1.z - value2.z;
  2897. return (x * x) + (y * y) + (z * z);
  2898. };
  2899. /**
  2900. * Returns a new Vector3 located at the center between "value1" and "value2".
  2901. */
  2902. Vector3.Center = function (value1, value2) {
  2903. var center = value1.add(value2);
  2904. center.scaleInPlace(0.5);
  2905. return center;
  2906. };
  2907. /**
  2908. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2909. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2910. * to something in order to rotate it from its local system to the given target system.
  2911. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2912. * Returns a new Vector3.
  2913. */
  2914. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2915. var rotation = Vector3.Zero();
  2916. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2917. return rotation;
  2918. };
  2919. /**
  2920. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2921. */
  2922. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2923. var quat = MathTmp.Quaternion[0];
  2924. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2925. quat.toEulerAnglesToRef(ref);
  2926. };
  2927. return Vector3;
  2928. }());
  2929. BABYLON.Vector3 = Vector3;
  2930. //Vector4 class created for EulerAngle class conversion to Quaternion
  2931. var Vector4 = /** @class */ (function () {
  2932. /**
  2933. * Creates a Vector4 object from the passed floats.
  2934. */
  2935. function Vector4(x, y, z, w) {
  2936. this.x = x;
  2937. this.y = y;
  2938. this.z = z;
  2939. this.w = w;
  2940. }
  2941. /**
  2942. * Returns the string with the Vector4 coordinates.
  2943. */
  2944. Vector4.prototype.toString = function () {
  2945. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2946. };
  2947. /**
  2948. * Returns the string "Vector4".
  2949. */
  2950. Vector4.prototype.getClassName = function () {
  2951. return "Vector4";
  2952. };
  2953. /**
  2954. * Returns the Vector4 hash code.
  2955. */
  2956. Vector4.prototype.getHashCode = function () {
  2957. var hash = this.x || 0;
  2958. hash = (hash * 397) ^ (this.y || 0);
  2959. hash = (hash * 397) ^ (this.z || 0);
  2960. hash = (hash * 397) ^ (this.w || 0);
  2961. return hash;
  2962. };
  2963. // Operators
  2964. /**
  2965. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2966. */
  2967. Vector4.prototype.asArray = function () {
  2968. var result = new Array();
  2969. this.toArray(result, 0);
  2970. return result;
  2971. };
  2972. /**
  2973. * Populates the passed array from the passed index with the Vector4 coordinates.
  2974. * Returns the Vector4.
  2975. */
  2976. Vector4.prototype.toArray = function (array, index) {
  2977. if (index === undefined) {
  2978. index = 0;
  2979. }
  2980. array[index] = this.x;
  2981. array[index + 1] = this.y;
  2982. array[index + 2] = this.z;
  2983. array[index + 3] = this.w;
  2984. return this;
  2985. };
  2986. /**
  2987. * Adds the passed vector to the current Vector4.
  2988. * Returns the updated Vector4.
  2989. */
  2990. Vector4.prototype.addInPlace = function (otherVector) {
  2991. this.x += otherVector.x;
  2992. this.y += otherVector.y;
  2993. this.z += otherVector.z;
  2994. this.w += otherVector.w;
  2995. return this;
  2996. };
  2997. /**
  2998. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2999. */
  3000. Vector4.prototype.add = function (otherVector) {
  3001. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3002. };
  3003. /**
  3004. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3005. * Returns the current Vector4.
  3006. */
  3007. Vector4.prototype.addToRef = function (otherVector, result) {
  3008. result.x = this.x + otherVector.x;
  3009. result.y = this.y + otherVector.y;
  3010. result.z = this.z + otherVector.z;
  3011. result.w = this.w + otherVector.w;
  3012. return this;
  3013. };
  3014. /**
  3015. * Subtract in place the passed vector from the current Vector4.
  3016. * Returns the updated Vector4.
  3017. */
  3018. Vector4.prototype.subtractInPlace = function (otherVector) {
  3019. this.x -= otherVector.x;
  3020. this.y -= otherVector.y;
  3021. this.z -= otherVector.z;
  3022. this.w -= otherVector.w;
  3023. return this;
  3024. };
  3025. /**
  3026. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3027. */
  3028. Vector4.prototype.subtract = function (otherVector) {
  3029. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3030. };
  3031. /**
  3032. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3033. * Returns the current Vector4.
  3034. */
  3035. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3036. result.x = this.x - otherVector.x;
  3037. result.y = this.y - otherVector.y;
  3038. result.z = this.z - otherVector.z;
  3039. result.w = this.w - otherVector.w;
  3040. return this;
  3041. };
  3042. /**
  3043. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3044. */
  3045. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3046. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3047. };
  3048. /**
  3049. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3050. * Returns the current Vector4.
  3051. */
  3052. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3053. result.x = this.x - x;
  3054. result.y = this.y - y;
  3055. result.z = this.z - z;
  3056. result.w = this.w - w;
  3057. return this;
  3058. };
  3059. /**
  3060. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3061. */
  3062. Vector4.prototype.negate = function () {
  3063. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3064. };
  3065. /**
  3066. * Multiplies the current Vector4 coordinates by scale (float).
  3067. * Returns the updated Vector4.
  3068. */
  3069. Vector4.prototype.scaleInPlace = function (scale) {
  3070. this.x *= scale;
  3071. this.y *= scale;
  3072. this.z *= scale;
  3073. this.w *= scale;
  3074. return this;
  3075. };
  3076. /**
  3077. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3078. */
  3079. Vector4.prototype.scale = function (scale) {
  3080. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3081. };
  3082. /**
  3083. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3084. * Returns the current Vector4.
  3085. */
  3086. Vector4.prototype.scaleToRef = function (scale, result) {
  3087. result.x = this.x * scale;
  3088. result.y = this.y * scale;
  3089. result.z = this.z * scale;
  3090. result.w = this.w * scale;
  3091. return this;
  3092. };
  3093. /**
  3094. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3095. */
  3096. Vector4.prototype.equals = function (otherVector) {
  3097. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3098. };
  3099. /**
  3100. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3101. */
  3102. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3103. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3104. return otherVector
  3105. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3106. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3107. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3108. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3109. };
  3110. /**
  3111. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3112. */
  3113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3114. return this.x === x && this.y === y && this.z === z && this.w === w;
  3115. };
  3116. /**
  3117. * Multiplies in place the current Vector4 by the passed one.
  3118. * Returns the updated Vector4.
  3119. */
  3120. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3121. this.x *= otherVector.x;
  3122. this.y *= otherVector.y;
  3123. this.z *= otherVector.z;
  3124. this.w *= otherVector.w;
  3125. return this;
  3126. };
  3127. /**
  3128. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3129. */
  3130. Vector4.prototype.multiply = function (otherVector) {
  3131. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3132. };
  3133. /**
  3134. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3135. * Returns the current Vector4.
  3136. */
  3137. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3138. result.x = this.x * otherVector.x;
  3139. result.y = this.y * otherVector.y;
  3140. result.z = this.z * otherVector.z;
  3141. result.w = this.w * otherVector.w;
  3142. return this;
  3143. };
  3144. /**
  3145. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3146. */
  3147. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3148. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3149. };
  3150. /**
  3151. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3152. */
  3153. Vector4.prototype.divide = function (otherVector) {
  3154. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3155. };
  3156. /**
  3157. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3158. * Returns the current Vector4.
  3159. */
  3160. Vector4.prototype.divideToRef = function (otherVector, result) {
  3161. result.x = this.x / otherVector.x;
  3162. result.y = this.y / otherVector.y;
  3163. result.z = this.z / otherVector.z;
  3164. result.w = this.w / otherVector.w;
  3165. return this;
  3166. };
  3167. /**
  3168. * Divides the current Vector3 coordinates by the passed ones.
  3169. * Returns the updated Vector3.
  3170. */
  3171. Vector4.prototype.divideInPlace = function (otherVector) {
  3172. return this.divideToRef(otherVector, this);
  3173. };
  3174. /**
  3175. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  3176. */
  3177. Vector4.prototype.MinimizeInPlace = function (other) {
  3178. if (other.x < this.x)
  3179. this.x = other.x;
  3180. if (other.y < this.y)
  3181. this.y = other.y;
  3182. if (other.z < this.z)
  3183. this.z = other.z;
  3184. if (other.w < this.w)
  3185. this.w = other.w;
  3186. return this;
  3187. };
  3188. /**
  3189. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  3190. */
  3191. Vector4.prototype.MaximizeInPlace = function (other) {
  3192. if (other.x > this.x)
  3193. this.x = other.x;
  3194. if (other.y > this.y)
  3195. this.y = other.y;
  3196. if (other.z > this.z)
  3197. this.z = other.z;
  3198. if (other.w > this.w)
  3199. this.w = other.w;
  3200. return this;
  3201. };
  3202. // Properties
  3203. /**
  3204. * Returns the Vector4 length (float).
  3205. */
  3206. Vector4.prototype.length = function () {
  3207. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3208. };
  3209. /**
  3210. * Returns the Vector4 squared length (float).
  3211. */
  3212. Vector4.prototype.lengthSquared = function () {
  3213. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3214. };
  3215. // Methods
  3216. /**
  3217. * Normalizes in place the Vector4.
  3218. * Returns the updated Vector4.
  3219. */
  3220. Vector4.prototype.normalize = function () {
  3221. var len = this.length();
  3222. if (len === 0)
  3223. return this;
  3224. var num = 1.0 / len;
  3225. this.x *= num;
  3226. this.y *= num;
  3227. this.z *= num;
  3228. this.w *= num;
  3229. return this;
  3230. };
  3231. /**
  3232. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3233. */
  3234. Vector4.prototype.toVector3 = function () {
  3235. return new Vector3(this.x, this.y, this.z);
  3236. };
  3237. /**
  3238. * Returns a new Vector4 copied from the current one.
  3239. */
  3240. Vector4.prototype.clone = function () {
  3241. return new Vector4(this.x, this.y, this.z, this.w);
  3242. };
  3243. /**
  3244. * Updates the current Vector4 with the passed one coordinates.
  3245. * Returns the updated Vector4.
  3246. */
  3247. Vector4.prototype.copyFrom = function (source) {
  3248. this.x = source.x;
  3249. this.y = source.y;
  3250. this.z = source.z;
  3251. this.w = source.w;
  3252. return this;
  3253. };
  3254. /**
  3255. * Updates the current Vector4 coordinates with the passed floats.
  3256. * Returns the updated Vector4.
  3257. */
  3258. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3259. this.x = x;
  3260. this.y = y;
  3261. this.z = z;
  3262. this.w = w;
  3263. return this;
  3264. };
  3265. /**
  3266. * Updates the current Vector4 coordinates with the passed floats.
  3267. * Returns the updated Vector4.
  3268. */
  3269. Vector4.prototype.set = function (x, y, z, w) {
  3270. return this.copyFromFloats(x, y, z, w);
  3271. };
  3272. // Statics
  3273. /**
  3274. * Returns a new Vector4 set from the starting index of the passed array.
  3275. */
  3276. Vector4.FromArray = function (array, offset) {
  3277. if (!offset) {
  3278. offset = 0;
  3279. }
  3280. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3281. };
  3282. /**
  3283. * Updates the passed vector "result" from the starting index of the passed array.
  3284. */
  3285. Vector4.FromArrayToRef = function (array, offset, result) {
  3286. result.x = array[offset];
  3287. result.y = array[offset + 1];
  3288. result.z = array[offset + 2];
  3289. result.w = array[offset + 3];
  3290. };
  3291. /**
  3292. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3293. */
  3294. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3295. Vector4.FromArrayToRef(array, offset, result);
  3296. };
  3297. /**
  3298. * Updates the passed vector "result" coordinates from the passed floats.
  3299. */
  3300. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3301. result.x = x;
  3302. result.y = y;
  3303. result.z = z;
  3304. result.w = w;
  3305. };
  3306. /**
  3307. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3308. */
  3309. Vector4.Zero = function () {
  3310. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3311. };
  3312. /**
  3313. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3314. */
  3315. Vector4.One = function () {
  3316. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3317. };
  3318. /**
  3319. * Returns a new normalized Vector4 from the passed one.
  3320. */
  3321. Vector4.Normalize = function (vector) {
  3322. var result = Vector4.Zero();
  3323. Vector4.NormalizeToRef(vector, result);
  3324. return result;
  3325. };
  3326. /**
  3327. * Updates the passed vector "result" from the normalization of the passed one.
  3328. */
  3329. Vector4.NormalizeToRef = function (vector, result) {
  3330. result.copyFrom(vector);
  3331. result.normalize();
  3332. };
  3333. Vector4.Minimize = function (left, right) {
  3334. var min = left.clone();
  3335. min.MinimizeInPlace(right);
  3336. return min;
  3337. };
  3338. Vector4.Maximize = function (left, right) {
  3339. var max = left.clone();
  3340. max.MaximizeInPlace(right);
  3341. return max;
  3342. };
  3343. /**
  3344. * Returns the distance (float) between the vectors "value1" and "value2".
  3345. */
  3346. Vector4.Distance = function (value1, value2) {
  3347. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3348. };
  3349. /**
  3350. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3351. */
  3352. Vector4.DistanceSquared = function (value1, value2) {
  3353. var x = value1.x - value2.x;
  3354. var y = value1.y - value2.y;
  3355. var z = value1.z - value2.z;
  3356. var w = value1.w - value2.w;
  3357. return (x * x) + (y * y) + (z * z) + (w * w);
  3358. };
  3359. /**
  3360. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3361. */
  3362. Vector4.Center = function (value1, value2) {
  3363. var center = value1.add(value2);
  3364. center.scaleInPlace(0.5);
  3365. return center;
  3366. };
  3367. /**
  3368. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3369. * This methods computes transformed normalized direction vectors only.
  3370. */
  3371. Vector4.TransformNormal = function (vector, transformation) {
  3372. var result = Vector4.Zero();
  3373. Vector4.TransformNormalToRef(vector, transformation, result);
  3374. return result;
  3375. };
  3376. /**
  3377. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3378. * This methods computes transformed normalized direction vectors only.
  3379. */
  3380. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3381. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3382. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3383. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3384. result.x = x;
  3385. result.y = y;
  3386. result.z = z;
  3387. result.w = vector.w;
  3388. };
  3389. /**
  3390. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3391. * This methods computes transformed normalized direction vectors only.
  3392. */
  3393. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3394. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3395. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3396. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3397. result.w = w;
  3398. };
  3399. return Vector4;
  3400. }());
  3401. BABYLON.Vector4 = Vector4;
  3402. var Size = /** @class */ (function () {
  3403. /**
  3404. * Creates a Size object from the passed width and height (floats).
  3405. */
  3406. function Size(width, height) {
  3407. this.width = width;
  3408. this.height = height;
  3409. }
  3410. // Returns a string with the Size width and height.
  3411. Size.prototype.toString = function () {
  3412. return "{W: " + this.width + ", H: " + this.height + "}";
  3413. };
  3414. /**
  3415. * Returns the string "Size"
  3416. */
  3417. Size.prototype.getClassName = function () {
  3418. return "Size";
  3419. };
  3420. /**
  3421. * Returns the Size hash code.
  3422. */
  3423. Size.prototype.getHashCode = function () {
  3424. var hash = this.width || 0;
  3425. hash = (hash * 397) ^ (this.height || 0);
  3426. return hash;
  3427. };
  3428. /**
  3429. * Updates the current size from the passed one.
  3430. * Returns the updated Size.
  3431. */
  3432. Size.prototype.copyFrom = function (src) {
  3433. this.width = src.width;
  3434. this.height = src.height;
  3435. };
  3436. /**
  3437. * Updates in place the current Size from the passed floats.
  3438. * Returns the updated Size.
  3439. */
  3440. Size.prototype.copyFromFloats = function (width, height) {
  3441. this.width = width;
  3442. this.height = height;
  3443. return this;
  3444. };
  3445. /**
  3446. * Updates in place the current Size from the passed floats.
  3447. * Returns the updated Size.
  3448. */
  3449. Size.prototype.set = function (width, height) {
  3450. return this.copyFromFloats(width, height);
  3451. };
  3452. /**
  3453. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3454. */
  3455. Size.prototype.multiplyByFloats = function (w, h) {
  3456. return new Size(this.width * w, this.height * h);
  3457. };
  3458. /**
  3459. * Returns a new Size copied from the passed one.
  3460. */
  3461. Size.prototype.clone = function () {
  3462. return new Size(this.width, this.height);
  3463. };
  3464. /**
  3465. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3466. */
  3467. Size.prototype.equals = function (other) {
  3468. if (!other) {
  3469. return false;
  3470. }
  3471. return (this.width === other.width) && (this.height === other.height);
  3472. };
  3473. Object.defineProperty(Size.prototype, "surface", {
  3474. /**
  3475. * Returns the surface of the Size : width * height (float).
  3476. */
  3477. get: function () {
  3478. return this.width * this.height;
  3479. },
  3480. enumerable: true,
  3481. configurable: true
  3482. });
  3483. /**
  3484. * Returns a new Size set to (0.0, 0.0)
  3485. */
  3486. Size.Zero = function () {
  3487. return new Size(0.0, 0.0);
  3488. };
  3489. /**
  3490. * Returns a new Size set as the addition result of the current Size and the passed one.
  3491. */
  3492. Size.prototype.add = function (otherSize) {
  3493. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3494. return r;
  3495. };
  3496. /**
  3497. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3498. */
  3499. Size.prototype.subtract = function (otherSize) {
  3500. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3501. return r;
  3502. };
  3503. /**
  3504. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3505. */
  3506. Size.Lerp = function (start, end, amount) {
  3507. var w = start.width + ((end.width - start.width) * amount);
  3508. var h = start.height + ((end.height - start.height) * amount);
  3509. return new Size(w, h);
  3510. };
  3511. return Size;
  3512. }());
  3513. BABYLON.Size = Size;
  3514. var Quaternion = /** @class */ (function () {
  3515. /**
  3516. * Creates a new Quaternion from the passed floats.
  3517. */
  3518. function Quaternion(x, y, z, w) {
  3519. if (x === void 0) { x = 0.0; }
  3520. if (y === void 0) { y = 0.0; }
  3521. if (z === void 0) { z = 0.0; }
  3522. if (w === void 0) { w = 1.0; }
  3523. this.x = x;
  3524. this.y = y;
  3525. this.z = z;
  3526. this.w = w;
  3527. }
  3528. /**
  3529. * Returns a string with the Quaternion coordinates.
  3530. */
  3531. Quaternion.prototype.toString = function () {
  3532. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3533. };
  3534. /**
  3535. * Returns the string "Quaternion".
  3536. */
  3537. Quaternion.prototype.getClassName = function () {
  3538. return "Quaternion";
  3539. };
  3540. /**
  3541. * Returns the Quaternion hash code.
  3542. */
  3543. Quaternion.prototype.getHashCode = function () {
  3544. var hash = this.x || 0;
  3545. hash = (hash * 397) ^ (this.y || 0);
  3546. hash = (hash * 397) ^ (this.z || 0);
  3547. hash = (hash * 397) ^ (this.w || 0);
  3548. return hash;
  3549. };
  3550. /**
  3551. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3552. */
  3553. Quaternion.prototype.asArray = function () {
  3554. return [this.x, this.y, this.z, this.w];
  3555. };
  3556. /**
  3557. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3558. */
  3559. Quaternion.prototype.equals = function (otherQuaternion) {
  3560. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3561. };
  3562. /**
  3563. * Returns a new Quaternion copied from the current one.
  3564. */
  3565. Quaternion.prototype.clone = function () {
  3566. return new Quaternion(this.x, this.y, this.z, this.w);
  3567. };
  3568. /**
  3569. * Updates the current Quaternion from the passed one coordinates.
  3570. * Returns the updated Quaterion.
  3571. */
  3572. Quaternion.prototype.copyFrom = function (other) {
  3573. this.x = other.x;
  3574. this.y = other.y;
  3575. this.z = other.z;
  3576. this.w = other.w;
  3577. return this;
  3578. };
  3579. /**
  3580. * Updates the current Quaternion from the passed float coordinates.
  3581. * Returns the updated Quaterion.
  3582. */
  3583. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3584. this.x = x;
  3585. this.y = y;
  3586. this.z = z;
  3587. this.w = w;
  3588. return this;
  3589. };
  3590. /**
  3591. * Updates the current Quaternion from the passed float coordinates.
  3592. * Returns the updated Quaterion.
  3593. */
  3594. Quaternion.prototype.set = function (x, y, z, w) {
  3595. return this.copyFromFloats(x, y, z, w);
  3596. };
  3597. /**
  3598. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3599. */
  3600. Quaternion.prototype.add = function (other) {
  3601. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3602. };
  3603. /**
  3604. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3605. */
  3606. Quaternion.prototype.subtract = function (other) {
  3607. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3608. };
  3609. /**
  3610. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3611. */
  3612. Quaternion.prototype.scale = function (value) {
  3613. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3614. };
  3615. /**
  3616. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3617. */
  3618. Quaternion.prototype.multiply = function (q1) {
  3619. var result = new Quaternion(0, 0, 0, 1.0);
  3620. this.multiplyToRef(q1, result);
  3621. return result;
  3622. };
  3623. /**
  3624. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3625. * Returns the current Quaternion.
  3626. */
  3627. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3628. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3629. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3630. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3631. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3632. result.copyFromFloats(x, y, z, w);
  3633. return this;
  3634. };
  3635. /**
  3636. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3637. * Returns the updated Quaternion.
  3638. */
  3639. Quaternion.prototype.multiplyInPlace = function (q1) {
  3640. this.multiplyToRef(q1, this);
  3641. return this;
  3642. };
  3643. /**
  3644. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3645. * Returns the current Quaternion.
  3646. */
  3647. Quaternion.prototype.conjugateToRef = function (ref) {
  3648. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3649. return this;
  3650. };
  3651. /**
  3652. * Conjugates in place the current Quaternion.
  3653. * Returns the updated Quaternion.
  3654. */
  3655. Quaternion.prototype.conjugateInPlace = function () {
  3656. this.x *= -1;
  3657. this.y *= -1;
  3658. this.z *= -1;
  3659. return this;
  3660. };
  3661. /**
  3662. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3663. */
  3664. Quaternion.prototype.conjugate = function () {
  3665. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3666. return result;
  3667. };
  3668. /**
  3669. * Returns the Quaternion length (float).
  3670. */
  3671. Quaternion.prototype.length = function () {
  3672. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3673. };
  3674. /**
  3675. * Normalize in place the current Quaternion.
  3676. * Returns the updated Quaternion.
  3677. */
  3678. Quaternion.prototype.normalize = function () {
  3679. var length = 1.0 / this.length();
  3680. this.x *= length;
  3681. this.y *= length;
  3682. this.z *= length;
  3683. this.w *= length;
  3684. return this;
  3685. };
  3686. /**
  3687. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3688. */
  3689. Quaternion.prototype.toEulerAngles = function (order) {
  3690. if (order === void 0) { order = "YZX"; }
  3691. var result = Vector3.Zero();
  3692. this.toEulerAnglesToRef(result, order);
  3693. return result;
  3694. };
  3695. /**
  3696. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3697. * Returns the current Quaternion.
  3698. */
  3699. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3700. if (order === void 0) { order = "YZX"; }
  3701. var qz = this.z;
  3702. var qx = this.x;
  3703. var qy = this.y;
  3704. var qw = this.w;
  3705. var sqw = qw * qw;
  3706. var sqz = qz * qz;
  3707. var sqx = qx * qx;
  3708. var sqy = qy * qy;
  3709. var zAxisY = qy * qz - qx * qw;
  3710. var limit = .4999999;
  3711. if (zAxisY < -limit) {
  3712. result.y = 2 * Math.atan2(qy, qw);
  3713. result.x = Math.PI / 2;
  3714. result.z = 0;
  3715. }
  3716. else if (zAxisY > limit) {
  3717. result.y = 2 * Math.atan2(qy, qw);
  3718. result.x = -Math.PI / 2;
  3719. result.z = 0;
  3720. }
  3721. else {
  3722. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3723. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3724. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3725. }
  3726. return this;
  3727. };
  3728. /**
  3729. * Updates the passed rotation matrix with the current Quaternion values.
  3730. * Returns the current Quaternion.
  3731. */
  3732. Quaternion.prototype.toRotationMatrix = function (result) {
  3733. var xx = this.x * this.x;
  3734. var yy = this.y * this.y;
  3735. var zz = this.z * this.z;
  3736. var xy = this.x * this.y;
  3737. var zw = this.z * this.w;
  3738. var zx = this.z * this.x;
  3739. var yw = this.y * this.w;
  3740. var yz = this.y * this.z;
  3741. var xw = this.x * this.w;
  3742. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3743. result.m[1] = 2.0 * (xy + zw);
  3744. result.m[2] = 2.0 * (zx - yw);
  3745. result.m[3] = 0;
  3746. result.m[4] = 2.0 * (xy - zw);
  3747. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3748. result.m[6] = 2.0 * (yz + xw);
  3749. result.m[7] = 0;
  3750. result.m[8] = 2.0 * (zx + yw);
  3751. result.m[9] = 2.0 * (yz - xw);
  3752. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3753. result.m[11] = 0;
  3754. result.m[12] = 0;
  3755. result.m[13] = 0;
  3756. result.m[14] = 0;
  3757. result.m[15] = 1.0;
  3758. result._markAsUpdated();
  3759. return this;
  3760. };
  3761. /**
  3762. * Updates the current Quaternion from the passed rotation matrix values.
  3763. * Returns the updated Quaternion.
  3764. */
  3765. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3766. Quaternion.FromRotationMatrixToRef(matrix, this);
  3767. return this;
  3768. };
  3769. // Statics
  3770. /**
  3771. * Returns a new Quaternion set from the passed rotation matrix values.
  3772. */
  3773. Quaternion.FromRotationMatrix = function (matrix) {
  3774. var result = new Quaternion();
  3775. Quaternion.FromRotationMatrixToRef(matrix, result);
  3776. return result;
  3777. };
  3778. /**
  3779. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3780. */
  3781. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3782. var data = matrix.m;
  3783. var m11 = data[0], m12 = data[4], m13 = data[8];
  3784. var m21 = data[1], m22 = data[5], m23 = data[9];
  3785. var m31 = data[2], m32 = data[6], m33 = data[10];
  3786. var trace = m11 + m22 + m33;
  3787. var s;
  3788. if (trace > 0) {
  3789. s = 0.5 / Math.sqrt(trace + 1.0);
  3790. result.w = 0.25 / s;
  3791. result.x = (m32 - m23) * s;
  3792. result.y = (m13 - m31) * s;
  3793. result.z = (m21 - m12) * s;
  3794. }
  3795. else if (m11 > m22 && m11 > m33) {
  3796. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3797. result.w = (m32 - m23) / s;
  3798. result.x = 0.25 * s;
  3799. result.y = (m12 + m21) / s;
  3800. result.z = (m13 + m31) / s;
  3801. }
  3802. else if (m22 > m33) {
  3803. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3804. result.w = (m13 - m31) / s;
  3805. result.x = (m12 + m21) / s;
  3806. result.y = 0.25 * s;
  3807. result.z = (m23 + m32) / s;
  3808. }
  3809. else {
  3810. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3811. result.w = (m21 - m12) / s;
  3812. result.x = (m13 + m31) / s;
  3813. result.y = (m23 + m32) / s;
  3814. result.z = 0.25 * s;
  3815. }
  3816. };
  3817. /**
  3818. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3819. */
  3820. Quaternion.Zero = function () {
  3821. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3822. };
  3823. /**
  3824. * Returns a new Quaternion as the inverted current Quaternion.
  3825. */
  3826. Quaternion.Inverse = function (q) {
  3827. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3828. };
  3829. /**
  3830. * Returns the identity Quaternion.
  3831. */
  3832. Quaternion.Identity = function () {
  3833. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3834. };
  3835. Quaternion.IsIdentity = function (quaternion) {
  3836. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3837. };
  3838. /**
  3839. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3840. */
  3841. Quaternion.RotationAxis = function (axis, angle) {
  3842. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3843. };
  3844. /**
  3845. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3846. */
  3847. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3848. var sin = Math.sin(angle / 2);
  3849. axis.normalize();
  3850. result.w = Math.cos(angle / 2);
  3851. result.x = axis.x * sin;
  3852. result.y = axis.y * sin;
  3853. result.z = axis.z * sin;
  3854. return result;
  3855. };
  3856. /**
  3857. * Retuns a new Quaternion set from the starting index of the passed array.
  3858. */
  3859. Quaternion.FromArray = function (array, offset) {
  3860. if (!offset) {
  3861. offset = 0;
  3862. }
  3863. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3864. };
  3865. /**
  3866. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3867. */
  3868. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3869. var q = new Quaternion();
  3870. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3871. return q;
  3872. };
  3873. /**
  3874. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3875. */
  3876. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3877. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3878. var halfRoll = roll * 0.5;
  3879. var halfPitch = pitch * 0.5;
  3880. var halfYaw = yaw * 0.5;
  3881. var sinRoll = Math.sin(halfRoll);
  3882. var cosRoll = Math.cos(halfRoll);
  3883. var sinPitch = Math.sin(halfPitch);
  3884. var cosPitch = Math.cos(halfPitch);
  3885. var sinYaw = Math.sin(halfYaw);
  3886. var cosYaw = Math.cos(halfYaw);
  3887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3891. };
  3892. /**
  3893. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3894. */
  3895. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3896. var result = new Quaternion();
  3897. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3898. return result;
  3899. };
  3900. /**
  3901. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3902. */
  3903. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3904. // Produces a quaternion from Euler angles in the z-x-z orientation
  3905. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3906. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3907. var halfBeta = beta * 0.5;
  3908. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3909. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3910. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3911. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3912. };
  3913. /**
  3914. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3915. * cf to Vector3.RotationFromAxis() documentation.
  3916. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3917. */
  3918. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3919. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3920. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3921. return quat;
  3922. };
  3923. /**
  3924. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3925. * cf to Vector3.RotationFromAxis() documentation.
  3926. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3927. */
  3928. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3929. var rotMat = MathTmp.Matrix[0];
  3930. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3931. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3932. };
  3933. Quaternion.Slerp = function (left, right, amount) {
  3934. var result = Quaternion.Identity();
  3935. Quaternion.SlerpToRef(left, right, amount, result);
  3936. return result;
  3937. };
  3938. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3939. var num2;
  3940. var num3;
  3941. var num = amount;
  3942. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3943. var flag = false;
  3944. if (num4 < 0) {
  3945. flag = true;
  3946. num4 = -num4;
  3947. }
  3948. if (num4 > 0.999999) {
  3949. num3 = 1 - num;
  3950. num2 = flag ? -num : num;
  3951. }
  3952. else {
  3953. var num5 = Math.acos(num4);
  3954. var num6 = (1.0 / Math.sin(num5));
  3955. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3956. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3957. }
  3958. result.x = (num3 * left.x) + (num2 * right.x);
  3959. result.y = (num3 * left.y) + (num2 * right.y);
  3960. result.z = (num3 * left.z) + (num2 * right.z);
  3961. result.w = (num3 * left.w) + (num2 * right.w);
  3962. };
  3963. /**
  3964. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3965. */
  3966. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3967. var squared = amount * amount;
  3968. var cubed = amount * squared;
  3969. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3970. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3971. var part3 = (cubed - (2.0 * squared)) + amount;
  3972. var part4 = cubed - squared;
  3973. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3974. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3975. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3976. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3977. return new Quaternion(x, y, z, w);
  3978. };
  3979. return Quaternion;
  3980. }());
  3981. BABYLON.Quaternion = Quaternion;
  3982. var Matrix = /** @class */ (function () {
  3983. function Matrix() {
  3984. this._isIdentity = false;
  3985. this._isIdentityDirty = true;
  3986. this.m = new Float32Array(16);
  3987. this._markAsUpdated();
  3988. }
  3989. Matrix.prototype._markAsUpdated = function () {
  3990. this.updateFlag = Matrix._updateFlagSeed++;
  3991. this._isIdentityDirty = true;
  3992. };
  3993. // Properties
  3994. /**
  3995. * Boolean : True is the matrix is the identity matrix
  3996. */
  3997. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3998. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3999. if (this._isIdentityDirty) {
  4000. this._isIdentityDirty = false;
  4001. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4002. this._isIdentity = false;
  4003. }
  4004. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4005. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4006. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4007. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4008. this._isIdentity = false;
  4009. }
  4010. else {
  4011. this._isIdentity = true;
  4012. }
  4013. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4014. this._isIdentity = false;
  4015. }
  4016. }
  4017. return this._isIdentity;
  4018. };
  4019. /**
  4020. * Returns the matrix determinant (float).
  4021. */
  4022. Matrix.prototype.determinant = function () {
  4023. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4024. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4025. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4026. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4027. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4028. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4029. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4030. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4031. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4032. };
  4033. // Methods
  4034. /**
  4035. * Returns the matrix underlying array.
  4036. */
  4037. Matrix.prototype.toArray = function () {
  4038. return this.m;
  4039. };
  4040. /**
  4041. * Returns the matrix underlying array.
  4042. */
  4043. Matrix.prototype.asArray = function () {
  4044. return this.toArray();
  4045. };
  4046. /**
  4047. * Inverts in place the Matrix.
  4048. * Returns the Matrix inverted.
  4049. */
  4050. Matrix.prototype.invert = function () {
  4051. this.invertToRef(this);
  4052. return this;
  4053. };
  4054. /**
  4055. * Sets all the matrix elements to zero.
  4056. * Returns the Matrix.
  4057. */
  4058. Matrix.prototype.reset = function () {
  4059. for (var index = 0; index < 16; index++) {
  4060. this.m[index] = 0.0;
  4061. }
  4062. this._markAsUpdated();
  4063. return this;
  4064. };
  4065. /**
  4066. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4067. */
  4068. Matrix.prototype.add = function (other) {
  4069. var result = new Matrix();
  4070. this.addToRef(other, result);
  4071. return result;
  4072. };
  4073. /**
  4074. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4075. * Returns the Matrix.
  4076. */
  4077. Matrix.prototype.addToRef = function (other, result) {
  4078. for (var index = 0; index < 16; index++) {
  4079. result.m[index] = this.m[index] + other.m[index];
  4080. }
  4081. result._markAsUpdated();
  4082. return this;
  4083. };
  4084. /**
  4085. * Adds in place the passed matrix to the current Matrix.
  4086. * Returns the updated Matrix.
  4087. */
  4088. Matrix.prototype.addToSelf = function (other) {
  4089. for (var index = 0; index < 16; index++) {
  4090. this.m[index] += other.m[index];
  4091. }
  4092. this._markAsUpdated();
  4093. return this;
  4094. };
  4095. /**
  4096. * Sets the passed matrix with the current inverted Matrix.
  4097. * Returns the unmodified current Matrix.
  4098. */
  4099. Matrix.prototype.invertToRef = function (other) {
  4100. var l1 = this.m[0];
  4101. var l2 = this.m[1];
  4102. var l3 = this.m[2];
  4103. var l4 = this.m[3];
  4104. var l5 = this.m[4];
  4105. var l6 = this.m[5];
  4106. var l7 = this.m[6];
  4107. var l8 = this.m[7];
  4108. var l9 = this.m[8];
  4109. var l10 = this.m[9];
  4110. var l11 = this.m[10];
  4111. var l12 = this.m[11];
  4112. var l13 = this.m[12];
  4113. var l14 = this.m[13];
  4114. var l15 = this.m[14];
  4115. var l16 = this.m[15];
  4116. var l17 = (l11 * l16) - (l12 * l15);
  4117. var l18 = (l10 * l16) - (l12 * l14);
  4118. var l19 = (l10 * l15) - (l11 * l14);
  4119. var l20 = (l9 * l16) - (l12 * l13);
  4120. var l21 = (l9 * l15) - (l11 * l13);
  4121. var l22 = (l9 * l14) - (l10 * l13);
  4122. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4123. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4124. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4125. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4126. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4127. var l28 = (l7 * l16) - (l8 * l15);
  4128. var l29 = (l6 * l16) - (l8 * l14);
  4129. var l30 = (l6 * l15) - (l7 * l14);
  4130. var l31 = (l5 * l16) - (l8 * l13);
  4131. var l32 = (l5 * l15) - (l7 * l13);
  4132. var l33 = (l5 * l14) - (l6 * l13);
  4133. var l34 = (l7 * l12) - (l8 * l11);
  4134. var l35 = (l6 * l12) - (l8 * l10);
  4135. var l36 = (l6 * l11) - (l7 * l10);
  4136. var l37 = (l5 * l12) - (l8 * l9);
  4137. var l38 = (l5 * l11) - (l7 * l9);
  4138. var l39 = (l5 * l10) - (l6 * l9);
  4139. other.m[0] = l23 * l27;
  4140. other.m[4] = l24 * l27;
  4141. other.m[8] = l25 * l27;
  4142. other.m[12] = l26 * l27;
  4143. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4144. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4145. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4146. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4147. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4148. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4149. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4150. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4151. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4152. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4153. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4154. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4155. other._markAsUpdated();
  4156. return this;
  4157. };
  4158. /**
  4159. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4160. * Returns the updated Matrix.
  4161. */
  4162. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4163. this.m[12] = x;
  4164. this.m[13] = y;
  4165. this.m[14] = z;
  4166. this._markAsUpdated();
  4167. return this;
  4168. };
  4169. /**
  4170. * Inserts the translation vector in the current Matrix.
  4171. * Returns the updated Matrix.
  4172. */
  4173. Matrix.prototype.setTranslation = function (vector3) {
  4174. this.m[12] = vector3.x;
  4175. this.m[13] = vector3.y;
  4176. this.m[14] = vector3.z;
  4177. this._markAsUpdated();
  4178. return this;
  4179. };
  4180. /**
  4181. * Returns a new Vector3 as the extracted translation from the Matrix.
  4182. */
  4183. Matrix.prototype.getTranslation = function () {
  4184. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4185. };
  4186. /**
  4187. * Fill a Vector3 with the extracted translation from the Matrix.
  4188. */
  4189. Matrix.prototype.getTranslationToRef = function (result) {
  4190. result.x = this.m[12];
  4191. result.y = this.m[13];
  4192. result.z = this.m[14];
  4193. return this;
  4194. };
  4195. /**
  4196. * Remove rotation and scaling part from the Matrix.
  4197. * Returns the updated Matrix.
  4198. */
  4199. Matrix.prototype.removeRotationAndScaling = function () {
  4200. this.setRowFromFloats(0, 1, 0, 0, 0);
  4201. this.setRowFromFloats(1, 0, 1, 0, 0);
  4202. this.setRowFromFloats(2, 0, 0, 1, 0);
  4203. return this;
  4204. };
  4205. /**
  4206. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4207. */
  4208. Matrix.prototype.multiply = function (other) {
  4209. var result = new Matrix();
  4210. this.multiplyToRef(other, result);
  4211. return result;
  4212. };
  4213. /**
  4214. * Updates the current Matrix from the passed one values.
  4215. * Returns the updated Matrix.
  4216. */
  4217. Matrix.prototype.copyFrom = function (other) {
  4218. for (var index = 0; index < 16; index++) {
  4219. this.m[index] = other.m[index];
  4220. }
  4221. this._markAsUpdated();
  4222. return this;
  4223. };
  4224. /**
  4225. * Populates the passed array from the starting index with the Matrix values.
  4226. * Returns the Matrix.
  4227. */
  4228. Matrix.prototype.copyToArray = function (array, offset) {
  4229. if (offset === void 0) { offset = 0; }
  4230. for (var index = 0; index < 16; index++) {
  4231. array[offset + index] = this.m[index];
  4232. }
  4233. return this;
  4234. };
  4235. /**
  4236. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4237. */
  4238. Matrix.prototype.multiplyToRef = function (other, result) {
  4239. this.multiplyToArray(other, result.m, 0);
  4240. result._markAsUpdated();
  4241. return this;
  4242. };
  4243. /**
  4244. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4245. */
  4246. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4247. var tm0 = this.m[0];
  4248. var tm1 = this.m[1];
  4249. var tm2 = this.m[2];
  4250. var tm3 = this.m[3];
  4251. var tm4 = this.m[4];
  4252. var tm5 = this.m[5];
  4253. var tm6 = this.m[6];
  4254. var tm7 = this.m[7];
  4255. var tm8 = this.m[8];
  4256. var tm9 = this.m[9];
  4257. var tm10 = this.m[10];
  4258. var tm11 = this.m[11];
  4259. var tm12 = this.m[12];
  4260. var tm13 = this.m[13];
  4261. var tm14 = this.m[14];
  4262. var tm15 = this.m[15];
  4263. var om0 = other.m[0];
  4264. var om1 = other.m[1];
  4265. var om2 = other.m[2];
  4266. var om3 = other.m[3];
  4267. var om4 = other.m[4];
  4268. var om5 = other.m[5];
  4269. var om6 = other.m[6];
  4270. var om7 = other.m[7];
  4271. var om8 = other.m[8];
  4272. var om9 = other.m[9];
  4273. var om10 = other.m[10];
  4274. var om11 = other.m[11];
  4275. var om12 = other.m[12];
  4276. var om13 = other.m[13];
  4277. var om14 = other.m[14];
  4278. var om15 = other.m[15];
  4279. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4280. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4281. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4282. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4283. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4284. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4285. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4286. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4287. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4288. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4289. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4290. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4291. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4292. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4293. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4294. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4295. return this;
  4296. };
  4297. /**
  4298. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4299. */
  4300. Matrix.prototype.equals = function (value) {
  4301. return value &&
  4302. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4303. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4304. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4305. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4306. };
  4307. /**
  4308. * Returns a new Matrix from the current Matrix.
  4309. */
  4310. Matrix.prototype.clone = function () {
  4311. 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]);
  4312. };
  4313. /**
  4314. * Returns the string "Matrix"
  4315. */
  4316. Matrix.prototype.getClassName = function () {
  4317. return "Matrix";
  4318. };
  4319. /**
  4320. * Returns the Matrix hash code.
  4321. */
  4322. Matrix.prototype.getHashCode = function () {
  4323. var hash = this.m[0] || 0;
  4324. for (var i = 1; i < 16; i++) {
  4325. hash = (hash * 397) ^ (this.m[i] || 0);
  4326. }
  4327. return hash;
  4328. };
  4329. /**
  4330. * Decomposes the current Matrix into :
  4331. * - a scale vector3 passed as a reference to update,
  4332. * - a rotation quaternion passed as a reference to update,
  4333. * - a translation vector3 passed as a reference to update.
  4334. * Returns the true if operation was successful.
  4335. */
  4336. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4337. translation.x = this.m[12];
  4338. translation.y = this.m[13];
  4339. translation.z = this.m[14];
  4340. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4341. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4342. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4343. if (this.determinant() <= 0) {
  4344. scale.y *= -1;
  4345. }
  4346. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4347. rotation.x = 0;
  4348. rotation.y = 0;
  4349. rotation.z = 0;
  4350. rotation.w = 1;
  4351. return false;
  4352. }
  4353. 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]);
  4354. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4355. return true;
  4356. };
  4357. /**
  4358. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4359. */
  4360. Matrix.prototype.getRotationMatrix = function () {
  4361. var result = Matrix.Identity();
  4362. this.getRotationMatrixToRef(result);
  4363. return result;
  4364. };
  4365. /**
  4366. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4367. * Returns the current Matrix.
  4368. */
  4369. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4370. var m = this.m;
  4371. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4372. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4373. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4374. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4375. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4376. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4377. 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);
  4378. return this;
  4379. };
  4380. // Statics
  4381. /**
  4382. * Returns a new Matrix set from the starting index of the passed array.
  4383. */
  4384. Matrix.FromArray = function (array, offset) {
  4385. var result = new Matrix();
  4386. if (!offset) {
  4387. offset = 0;
  4388. }
  4389. Matrix.FromArrayToRef(array, offset, result);
  4390. return result;
  4391. };
  4392. /**
  4393. * Sets the passed "result" matrix from the starting index of the passed array.
  4394. */
  4395. Matrix.FromArrayToRef = function (array, offset, result) {
  4396. for (var index = 0; index < 16; index++) {
  4397. result.m[index] = array[index + offset];
  4398. }
  4399. result._markAsUpdated();
  4400. };
  4401. /**
  4402. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4403. */
  4404. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4405. for (var index = 0; index < 16; index++) {
  4406. result.m[index] = array[index + offset] * scale;
  4407. }
  4408. result._markAsUpdated();
  4409. };
  4410. /**
  4411. * Sets the passed matrix "result" with the 16 passed floats.
  4412. */
  4413. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4414. result.m[0] = initialM11;
  4415. result.m[1] = initialM12;
  4416. result.m[2] = initialM13;
  4417. result.m[3] = initialM14;
  4418. result.m[4] = initialM21;
  4419. result.m[5] = initialM22;
  4420. result.m[6] = initialM23;
  4421. result.m[7] = initialM24;
  4422. result.m[8] = initialM31;
  4423. result.m[9] = initialM32;
  4424. result.m[10] = initialM33;
  4425. result.m[11] = initialM34;
  4426. result.m[12] = initialM41;
  4427. result.m[13] = initialM42;
  4428. result.m[14] = initialM43;
  4429. result.m[15] = initialM44;
  4430. result._markAsUpdated();
  4431. };
  4432. /**
  4433. * Returns the index-th row of the current matrix as a new Vector4.
  4434. */
  4435. Matrix.prototype.getRow = function (index) {
  4436. if (index < 0 || index > 3) {
  4437. return null;
  4438. }
  4439. var i = index * 4;
  4440. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4441. };
  4442. /**
  4443. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4444. * Returns the updated Matrix.
  4445. */
  4446. Matrix.prototype.setRow = function (index, row) {
  4447. if (index < 0 || index > 3) {
  4448. return this;
  4449. }
  4450. var i = index * 4;
  4451. this.m[i + 0] = row.x;
  4452. this.m[i + 1] = row.y;
  4453. this.m[i + 2] = row.z;
  4454. this.m[i + 3] = row.w;
  4455. this._markAsUpdated();
  4456. return this;
  4457. };
  4458. /**
  4459. * Compute the transpose of the matrix.
  4460. * Returns a new Matrix.
  4461. */
  4462. Matrix.prototype.transpose = function () {
  4463. return Matrix.Transpose(this);
  4464. };
  4465. /**
  4466. * Compute the transpose of the matrix.
  4467. * Returns the current matrix.
  4468. */
  4469. Matrix.prototype.transposeToRef = function (result) {
  4470. Matrix.TransposeToRef(this, result);
  4471. return this;
  4472. };
  4473. /**
  4474. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4475. * Returns the updated Matrix.
  4476. */
  4477. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4478. if (index < 0 || index > 3) {
  4479. return this;
  4480. }
  4481. var i = index * 4;
  4482. this.m[i + 0] = x;
  4483. this.m[i + 1] = y;
  4484. this.m[i + 2] = z;
  4485. this.m[i + 3] = w;
  4486. this._markAsUpdated();
  4487. return this;
  4488. };
  4489. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4490. /**
  4491. * Static identity matrix to be used as readonly matrix
  4492. * Must not be updated.
  4493. */
  4494. get: function () {
  4495. return Matrix._identityReadOnly;
  4496. },
  4497. enumerable: true,
  4498. configurable: true
  4499. });
  4500. /**
  4501. * Returns a new Matrix set from the 16 passed floats.
  4502. */
  4503. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4504. var result = new Matrix();
  4505. result.m[0] = initialM11;
  4506. result.m[1] = initialM12;
  4507. result.m[2] = initialM13;
  4508. result.m[3] = initialM14;
  4509. result.m[4] = initialM21;
  4510. result.m[5] = initialM22;
  4511. result.m[6] = initialM23;
  4512. result.m[7] = initialM24;
  4513. result.m[8] = initialM31;
  4514. result.m[9] = initialM32;
  4515. result.m[10] = initialM33;
  4516. result.m[11] = initialM34;
  4517. result.m[12] = initialM41;
  4518. result.m[13] = initialM42;
  4519. result.m[14] = initialM43;
  4520. result.m[15] = initialM44;
  4521. return result;
  4522. };
  4523. /**
  4524. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4525. */
  4526. Matrix.Compose = function (scale, rotation, translation) {
  4527. var result = Matrix.Identity();
  4528. Matrix.ComposeToRef(scale, rotation, translation, result);
  4529. return result;
  4530. };
  4531. /**
  4532. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4533. */
  4534. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4535. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4536. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4537. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4538. result.setTranslation(translation);
  4539. };
  4540. /**
  4541. * Returns a new indentity Matrix.
  4542. */
  4543. Matrix.Identity = function () {
  4544. 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);
  4545. };
  4546. /**
  4547. * Sets the passed "result" as an identity matrix.
  4548. */
  4549. Matrix.IdentityToRef = function (result) {
  4550. 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);
  4551. };
  4552. /**
  4553. * Returns a new zero Matrix.
  4554. */
  4555. Matrix.Zero = function () {
  4556. 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);
  4557. };
  4558. /**
  4559. * Returns a new rotation matrix for "angle" radians around the X axis.
  4560. */
  4561. Matrix.RotationX = function (angle) {
  4562. var result = new Matrix();
  4563. Matrix.RotationXToRef(angle, result);
  4564. return result;
  4565. };
  4566. /**
  4567. * Returns a new Matrix as the passed inverted one.
  4568. */
  4569. Matrix.Invert = function (source) {
  4570. var result = new Matrix();
  4571. source.invertToRef(result);
  4572. return result;
  4573. };
  4574. /**
  4575. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4576. */
  4577. Matrix.RotationXToRef = function (angle, result) {
  4578. var s = Math.sin(angle);
  4579. var c = Math.cos(angle);
  4580. result.m[0] = 1.0;
  4581. result.m[15] = 1.0;
  4582. result.m[5] = c;
  4583. result.m[10] = c;
  4584. result.m[9] = -s;
  4585. result.m[6] = s;
  4586. result.m[1] = 0.0;
  4587. result.m[2] = 0.0;
  4588. result.m[3] = 0.0;
  4589. result.m[4] = 0.0;
  4590. result.m[7] = 0.0;
  4591. result.m[8] = 0.0;
  4592. result.m[11] = 0.0;
  4593. result.m[12] = 0.0;
  4594. result.m[13] = 0.0;
  4595. result.m[14] = 0.0;
  4596. result._markAsUpdated();
  4597. };
  4598. /**
  4599. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4600. */
  4601. Matrix.RotationY = function (angle) {
  4602. var result = new Matrix();
  4603. Matrix.RotationYToRef(angle, result);
  4604. return result;
  4605. };
  4606. /**
  4607. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4608. */
  4609. Matrix.RotationYToRef = function (angle, result) {
  4610. var s = Math.sin(angle);
  4611. var c = Math.cos(angle);
  4612. result.m[5] = 1.0;
  4613. result.m[15] = 1.0;
  4614. result.m[0] = c;
  4615. result.m[2] = -s;
  4616. result.m[8] = s;
  4617. result.m[10] = c;
  4618. result.m[1] = 0.0;
  4619. result.m[3] = 0.0;
  4620. result.m[4] = 0.0;
  4621. result.m[6] = 0.0;
  4622. result.m[7] = 0.0;
  4623. result.m[9] = 0.0;
  4624. result.m[11] = 0.0;
  4625. result.m[12] = 0.0;
  4626. result.m[13] = 0.0;
  4627. result.m[14] = 0.0;
  4628. result._markAsUpdated();
  4629. };
  4630. /**
  4631. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4632. */
  4633. Matrix.RotationZ = function (angle) {
  4634. var result = new Matrix();
  4635. Matrix.RotationZToRef(angle, result);
  4636. return result;
  4637. };
  4638. /**
  4639. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4640. */
  4641. Matrix.RotationZToRef = function (angle, result) {
  4642. var s = Math.sin(angle);
  4643. var c = Math.cos(angle);
  4644. result.m[10] = 1.0;
  4645. result.m[15] = 1.0;
  4646. result.m[0] = c;
  4647. result.m[1] = s;
  4648. result.m[4] = -s;
  4649. result.m[5] = c;
  4650. result.m[2] = 0.0;
  4651. result.m[3] = 0.0;
  4652. result.m[6] = 0.0;
  4653. result.m[7] = 0.0;
  4654. result.m[8] = 0.0;
  4655. result.m[9] = 0.0;
  4656. result.m[11] = 0.0;
  4657. result.m[12] = 0.0;
  4658. result.m[13] = 0.0;
  4659. result.m[14] = 0.0;
  4660. result._markAsUpdated();
  4661. };
  4662. /**
  4663. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4664. */
  4665. Matrix.RotationAxis = function (axis, angle) {
  4666. var result = Matrix.Zero();
  4667. Matrix.RotationAxisToRef(axis, angle, result);
  4668. return result;
  4669. };
  4670. /**
  4671. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4672. */
  4673. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4674. var s = Math.sin(-angle);
  4675. var c = Math.cos(-angle);
  4676. var c1 = 1 - c;
  4677. axis.normalize();
  4678. result.m[0] = (axis.x * axis.x) * c1 + c;
  4679. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4680. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4681. result.m[3] = 0.0;
  4682. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4683. result.m[5] = (axis.y * axis.y) * c1 + c;
  4684. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4685. result.m[7] = 0.0;
  4686. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4687. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4688. result.m[10] = (axis.z * axis.z) * c1 + c;
  4689. result.m[11] = 0.0;
  4690. result.m[15] = 1.0;
  4691. result._markAsUpdated();
  4692. };
  4693. /**
  4694. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4695. */
  4696. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4697. var result = new Matrix();
  4698. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4699. return result;
  4700. };
  4701. /**
  4702. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4703. */
  4704. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4705. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4706. this._tempQuaternion.toRotationMatrix(result);
  4707. };
  4708. /**
  4709. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4710. */
  4711. Matrix.Scaling = function (x, y, z) {
  4712. var result = Matrix.Zero();
  4713. Matrix.ScalingToRef(x, y, z, result);
  4714. return result;
  4715. };
  4716. /**
  4717. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4718. */
  4719. Matrix.ScalingToRef = function (x, y, z, result) {
  4720. result.m[0] = x;
  4721. result.m[1] = 0.0;
  4722. result.m[2] = 0.0;
  4723. result.m[3] = 0.0;
  4724. result.m[4] = 0.0;
  4725. result.m[5] = y;
  4726. result.m[6] = 0.0;
  4727. result.m[7] = 0.0;
  4728. result.m[8] = 0.0;
  4729. result.m[9] = 0.0;
  4730. result.m[10] = z;
  4731. result.m[11] = 0.0;
  4732. result.m[12] = 0.0;
  4733. result.m[13] = 0.0;
  4734. result.m[14] = 0.0;
  4735. result.m[15] = 1.0;
  4736. result._markAsUpdated();
  4737. };
  4738. /**
  4739. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4740. */
  4741. Matrix.Translation = function (x, y, z) {
  4742. var result = Matrix.Identity();
  4743. Matrix.TranslationToRef(x, y, z, result);
  4744. return result;
  4745. };
  4746. /**
  4747. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4748. */
  4749. Matrix.TranslationToRef = function (x, y, z, result) {
  4750. 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);
  4751. };
  4752. /**
  4753. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4754. */
  4755. Matrix.Lerp = function (startValue, endValue, gradient) {
  4756. var result = Matrix.Zero();
  4757. for (var index = 0; index < 16; index++) {
  4758. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4759. }
  4760. result._markAsUpdated();
  4761. return result;
  4762. };
  4763. /**
  4764. * Returns a new Matrix whose values are computed by :
  4765. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4766. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4767. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4768. */
  4769. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4770. var startScale = new Vector3(0, 0, 0);
  4771. var startRotation = new Quaternion();
  4772. var startTranslation = new Vector3(0, 0, 0);
  4773. startValue.decompose(startScale, startRotation, startTranslation);
  4774. var endScale = new Vector3(0, 0, 0);
  4775. var endRotation = new Quaternion();
  4776. var endTranslation = new Vector3(0, 0, 0);
  4777. endValue.decompose(endScale, endRotation, endTranslation);
  4778. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4779. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4780. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4781. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4782. };
  4783. /**
  4784. * 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".
  4785. * This methods works for a Left-Handed system.
  4786. */
  4787. Matrix.LookAtLH = function (eye, target, up) {
  4788. var result = Matrix.Zero();
  4789. Matrix.LookAtLHToRef(eye, target, up, result);
  4790. return result;
  4791. };
  4792. /**
  4793. * 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".
  4794. * This methods works for a Left-Handed system.
  4795. */
  4796. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4797. // Z axis
  4798. target.subtractToRef(eye, this._zAxis);
  4799. this._zAxis.normalize();
  4800. // X axis
  4801. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4802. if (this._xAxis.lengthSquared() === 0) {
  4803. this._xAxis.x = 1.0;
  4804. }
  4805. else {
  4806. this._xAxis.normalize();
  4807. }
  4808. // Y axis
  4809. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4810. this._yAxis.normalize();
  4811. // Eye angles
  4812. var ex = -Vector3.Dot(this._xAxis, eye);
  4813. var ey = -Vector3.Dot(this._yAxis, eye);
  4814. var ez = -Vector3.Dot(this._zAxis, eye);
  4815. 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);
  4816. };
  4817. /**
  4818. * 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".
  4819. * This methods works for a Right-Handed system.
  4820. */
  4821. Matrix.LookAtRH = function (eye, target, up) {
  4822. var result = Matrix.Zero();
  4823. Matrix.LookAtRHToRef(eye, target, up, result);
  4824. return result;
  4825. };
  4826. /**
  4827. * 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".
  4828. * This methods works for a Left-Handed system.
  4829. */
  4830. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4831. // Z axis
  4832. eye.subtractToRef(target, this._zAxis);
  4833. this._zAxis.normalize();
  4834. // X axis
  4835. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4836. if (this._xAxis.lengthSquared() === 0) {
  4837. this._xAxis.x = 1.0;
  4838. }
  4839. else {
  4840. this._xAxis.normalize();
  4841. }
  4842. // Y axis
  4843. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4844. this._yAxis.normalize();
  4845. // Eye angles
  4846. var ex = -Vector3.Dot(this._xAxis, eye);
  4847. var ey = -Vector3.Dot(this._yAxis, eye);
  4848. var ez = -Vector3.Dot(this._zAxis, eye);
  4849. 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);
  4850. };
  4851. /**
  4852. * 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.
  4853. */
  4854. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4855. var matrix = Matrix.Zero();
  4856. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4857. return matrix;
  4858. };
  4859. /**
  4860. * 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.
  4861. */
  4862. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4863. var n = znear;
  4864. var f = zfar;
  4865. var a = 2.0 / width;
  4866. var b = 2.0 / height;
  4867. var c = 2.0 / (f - n);
  4868. var d = -(f + n) / (f - n);
  4869. 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);
  4870. };
  4871. /**
  4872. * 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.
  4873. */
  4874. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4875. var matrix = Matrix.Zero();
  4876. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4877. return matrix;
  4878. };
  4879. /**
  4880. * 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.
  4881. */
  4882. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4883. var n = znear;
  4884. var f = zfar;
  4885. var a = 2.0 / (right - left);
  4886. var b = 2.0 / (top - bottom);
  4887. var c = 2.0 / (f - n);
  4888. var d = -(f + n) / (f - n);
  4889. var i0 = (left + right) / (left - right);
  4890. var i1 = (top + bottom) / (bottom - top);
  4891. 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);
  4892. };
  4893. /**
  4894. * 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.
  4895. */
  4896. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4897. var matrix = Matrix.Zero();
  4898. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4899. return matrix;
  4900. };
  4901. /**
  4902. * 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.
  4903. */
  4904. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4905. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4906. result.m[10] *= -1.0;
  4907. };
  4908. /**
  4909. * 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.
  4910. */
  4911. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4912. var matrix = Matrix.Zero();
  4913. var n = znear;
  4914. var f = zfar;
  4915. var a = 2.0 * n / width;
  4916. var b = 2.0 * n / height;
  4917. var c = (f + n) / (f - n);
  4918. var d = -2.0 * f * n / (f - n);
  4919. 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);
  4920. return matrix;
  4921. };
  4922. /**
  4923. * 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.
  4924. */
  4925. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4926. var matrix = Matrix.Zero();
  4927. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4928. return matrix;
  4929. };
  4930. /**
  4931. * 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.
  4932. */
  4933. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4934. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4935. var n = znear;
  4936. var f = zfar;
  4937. var t = 1.0 / (Math.tan(fov * 0.5));
  4938. var a = isVerticalFovFixed ? (t / aspect) : t;
  4939. var b = isVerticalFovFixed ? t : (t * aspect);
  4940. var c = (f + n) / (f - n);
  4941. var d = -2.0 * f * n / (f - n);
  4942. 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);
  4943. };
  4944. /**
  4945. * 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.
  4946. */
  4947. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4948. var matrix = Matrix.Zero();
  4949. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4950. return matrix;
  4951. };
  4952. /**
  4953. * 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.
  4954. */
  4955. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4956. //alternatively this could be expressed as:
  4957. // m = PerspectiveFovLHToRef
  4958. // m[10] *= -1.0;
  4959. // m[11] *= -1.0;
  4960. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4961. var n = znear;
  4962. var f = zfar;
  4963. var t = 1.0 / (Math.tan(fov * 0.5));
  4964. var a = isVerticalFovFixed ? (t / aspect) : t;
  4965. var b = isVerticalFovFixed ? t : (t * aspect);
  4966. var c = -(f + n) / (f - n);
  4967. var d = -2 * f * n / (f - n);
  4968. 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);
  4969. };
  4970. /**
  4971. * 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.
  4972. */
  4973. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4974. if (rightHanded === void 0) { rightHanded = false; }
  4975. var rightHandedFactor = rightHanded ? -1 : 1;
  4976. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4977. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4978. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4979. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4980. var xScale = 2.0 / (leftTan + rightTan);
  4981. var yScale = 2.0 / (upTan + downTan);
  4982. result.m[0] = xScale;
  4983. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4984. result.m[5] = yScale;
  4985. result.m[6] = result.m[7] = 0.0;
  4986. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4987. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4988. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4989. result.m[10] = -zfar / (znear - zfar);
  4990. result.m[11] = 1.0 * rightHandedFactor;
  4991. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4992. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4993. // result.m[14] = (znear * zfar) / (znear - zfar);
  4994. result._markAsUpdated();
  4995. };
  4996. /**
  4997. * Returns the final transformation matrix : world * view * projection * viewport
  4998. */
  4999. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5000. var cw = viewport.width;
  5001. var ch = viewport.height;
  5002. var cx = viewport.x;
  5003. var cy = viewport.y;
  5004. 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);
  5005. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5006. };
  5007. /**
  5008. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5009. */
  5010. Matrix.GetAsMatrix2x2 = function (matrix) {
  5011. return new Float32Array([
  5012. matrix.m[0], matrix.m[1],
  5013. matrix.m[4], matrix.m[5]
  5014. ]);
  5015. };
  5016. /**
  5017. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5018. */
  5019. Matrix.GetAsMatrix3x3 = function (matrix) {
  5020. return new Float32Array([
  5021. matrix.m[0], matrix.m[1], matrix.m[2],
  5022. matrix.m[4], matrix.m[5], matrix.m[6],
  5023. matrix.m[8], matrix.m[9], matrix.m[10]
  5024. ]);
  5025. };
  5026. /**
  5027. * Compute the transpose of the passed Matrix.
  5028. * Returns a new Matrix.
  5029. */
  5030. Matrix.Transpose = function (matrix) {
  5031. var result = new Matrix();
  5032. Matrix.TransposeToRef(matrix, result);
  5033. return result;
  5034. };
  5035. /**
  5036. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5037. */
  5038. Matrix.TransposeToRef = function (matrix, result) {
  5039. result.m[0] = matrix.m[0];
  5040. result.m[1] = matrix.m[4];
  5041. result.m[2] = matrix.m[8];
  5042. result.m[3] = matrix.m[12];
  5043. result.m[4] = matrix.m[1];
  5044. result.m[5] = matrix.m[5];
  5045. result.m[6] = matrix.m[9];
  5046. result.m[7] = matrix.m[13];
  5047. result.m[8] = matrix.m[2];
  5048. result.m[9] = matrix.m[6];
  5049. result.m[10] = matrix.m[10];
  5050. result.m[11] = matrix.m[14];
  5051. result.m[12] = matrix.m[3];
  5052. result.m[13] = matrix.m[7];
  5053. result.m[14] = matrix.m[11];
  5054. result.m[15] = matrix.m[15];
  5055. };
  5056. /**
  5057. * Returns a new Matrix as the reflection matrix across the passed plane.
  5058. */
  5059. Matrix.Reflection = function (plane) {
  5060. var matrix = new Matrix();
  5061. Matrix.ReflectionToRef(plane, matrix);
  5062. return matrix;
  5063. };
  5064. /**
  5065. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5066. */
  5067. Matrix.ReflectionToRef = function (plane, result) {
  5068. plane.normalize();
  5069. var x = plane.normal.x;
  5070. var y = plane.normal.y;
  5071. var z = plane.normal.z;
  5072. var temp = -2 * x;
  5073. var temp2 = -2 * y;
  5074. var temp3 = -2 * z;
  5075. result.m[0] = (temp * x) + 1;
  5076. result.m[1] = temp2 * x;
  5077. result.m[2] = temp3 * x;
  5078. result.m[3] = 0.0;
  5079. result.m[4] = temp * y;
  5080. result.m[5] = (temp2 * y) + 1;
  5081. result.m[6] = temp3 * y;
  5082. result.m[7] = 0.0;
  5083. result.m[8] = temp * z;
  5084. result.m[9] = temp2 * z;
  5085. result.m[10] = (temp3 * z) + 1;
  5086. result.m[11] = 0.0;
  5087. result.m[12] = temp * plane.d;
  5088. result.m[13] = temp2 * plane.d;
  5089. result.m[14] = temp3 * plane.d;
  5090. result.m[15] = 1.0;
  5091. result._markAsUpdated();
  5092. };
  5093. /**
  5094. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5095. */
  5096. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5097. result.m[0] = xaxis.x;
  5098. result.m[1] = xaxis.y;
  5099. result.m[2] = xaxis.z;
  5100. result.m[3] = 0.0;
  5101. result.m[4] = yaxis.x;
  5102. result.m[5] = yaxis.y;
  5103. result.m[6] = yaxis.z;
  5104. result.m[7] = 0.0;
  5105. result.m[8] = zaxis.x;
  5106. result.m[9] = zaxis.y;
  5107. result.m[10] = zaxis.z;
  5108. result.m[11] = 0.0;
  5109. result.m[12] = 0.0;
  5110. result.m[13] = 0.0;
  5111. result.m[14] = 0.0;
  5112. result.m[15] = 1.0;
  5113. result._markAsUpdated();
  5114. };
  5115. /**
  5116. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5117. */
  5118. Matrix.FromQuaternionToRef = function (quat, result) {
  5119. var xx = quat.x * quat.x;
  5120. var yy = quat.y * quat.y;
  5121. var zz = quat.z * quat.z;
  5122. var xy = quat.x * quat.y;
  5123. var zw = quat.z * quat.w;
  5124. var zx = quat.z * quat.x;
  5125. var yw = quat.y * quat.w;
  5126. var yz = quat.y * quat.z;
  5127. var xw = quat.x * quat.w;
  5128. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5129. result.m[1] = 2.0 * (xy + zw);
  5130. result.m[2] = 2.0 * (zx - yw);
  5131. result.m[3] = 0.0;
  5132. result.m[4] = 2.0 * (xy - zw);
  5133. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5134. result.m[6] = 2.0 * (yz + xw);
  5135. result.m[7] = 0.0;
  5136. result.m[8] = 2.0 * (zx + yw);
  5137. result.m[9] = 2.0 * (yz - xw);
  5138. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5139. result.m[11] = 0.0;
  5140. result.m[12] = 0.0;
  5141. result.m[13] = 0.0;
  5142. result.m[14] = 0.0;
  5143. result.m[15] = 1.0;
  5144. result._markAsUpdated();
  5145. };
  5146. Matrix._tempQuaternion = new Quaternion();
  5147. Matrix._xAxis = Vector3.Zero();
  5148. Matrix._yAxis = Vector3.Zero();
  5149. Matrix._zAxis = Vector3.Zero();
  5150. Matrix._updateFlagSeed = 0;
  5151. Matrix._identityReadOnly = Matrix.Identity();
  5152. return Matrix;
  5153. }());
  5154. BABYLON.Matrix = Matrix;
  5155. var Plane = /** @class */ (function () {
  5156. /**
  5157. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5158. */
  5159. function Plane(a, b, c, d) {
  5160. this.normal = new Vector3(a, b, c);
  5161. this.d = d;
  5162. }
  5163. /**
  5164. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5165. */
  5166. Plane.prototype.asArray = function () {
  5167. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5168. };
  5169. // Methods
  5170. /**
  5171. * Returns a new plane copied from the current Plane.
  5172. */
  5173. Plane.prototype.clone = function () {
  5174. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5175. };
  5176. /**
  5177. * Returns the string "Plane".
  5178. */
  5179. Plane.prototype.getClassName = function () {
  5180. return "Plane";
  5181. };
  5182. /**
  5183. * Returns the Plane hash code.
  5184. */
  5185. Plane.prototype.getHashCode = function () {
  5186. var hash = this.normal.getHashCode();
  5187. hash = (hash * 397) ^ (this.d || 0);
  5188. return hash;
  5189. };
  5190. /**
  5191. * Normalize the current Plane in place.
  5192. * Returns the updated Plane.
  5193. */
  5194. Plane.prototype.normalize = function () {
  5195. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5196. var magnitude = 0.0;
  5197. if (norm !== 0) {
  5198. magnitude = 1.0 / norm;
  5199. }
  5200. this.normal.x *= magnitude;
  5201. this.normal.y *= magnitude;
  5202. this.normal.z *= magnitude;
  5203. this.d *= magnitude;
  5204. return this;
  5205. };
  5206. /**
  5207. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5208. */
  5209. Plane.prototype.transform = function (transformation) {
  5210. var transposedMatrix = Matrix.Transpose(transformation);
  5211. var x = this.normal.x;
  5212. var y = this.normal.y;
  5213. var z = this.normal.z;
  5214. var d = this.d;
  5215. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5216. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5217. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5218. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5219. return new Plane(normalX, normalY, normalZ, finalD);
  5220. };
  5221. /**
  5222. * Returns the dot product (float) of the point coordinates and the plane normal.
  5223. */
  5224. Plane.prototype.dotCoordinate = function (point) {
  5225. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5226. };
  5227. /**
  5228. * Updates the current Plane from the plane defined by the three passed points.
  5229. * Returns the updated Plane.
  5230. */
  5231. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5232. var x1 = point2.x - point1.x;
  5233. var y1 = point2.y - point1.y;
  5234. var z1 = point2.z - point1.z;
  5235. var x2 = point3.x - point1.x;
  5236. var y2 = point3.y - point1.y;
  5237. var z2 = point3.z - point1.z;
  5238. var yz = (y1 * z2) - (z1 * y2);
  5239. var xz = (z1 * x2) - (x1 * z2);
  5240. var xy = (x1 * y2) - (y1 * x2);
  5241. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5242. var invPyth;
  5243. if (pyth !== 0) {
  5244. invPyth = 1.0 / pyth;
  5245. }
  5246. else {
  5247. invPyth = 0.0;
  5248. }
  5249. this.normal.x = yz * invPyth;
  5250. this.normal.y = xz * invPyth;
  5251. this.normal.z = xy * invPyth;
  5252. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5253. return this;
  5254. };
  5255. /**
  5256. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5257. */
  5258. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5259. var dot = Vector3.Dot(this.normal, direction);
  5260. return (dot <= epsilon);
  5261. };
  5262. /**
  5263. * Returns the signed distance (float) from the passed point to the Plane.
  5264. */
  5265. Plane.prototype.signedDistanceTo = function (point) {
  5266. return Vector3.Dot(point, this.normal) + this.d;
  5267. };
  5268. // Statics
  5269. /**
  5270. * Returns a new Plane from the passed array.
  5271. */
  5272. Plane.FromArray = function (array) {
  5273. return new Plane(array[0], array[1], array[2], array[3]);
  5274. };
  5275. /**
  5276. * Returns a new Plane defined by the three passed points.
  5277. */
  5278. Plane.FromPoints = function (point1, point2, point3) {
  5279. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5280. result.copyFromPoints(point1, point2, point3);
  5281. return result;
  5282. };
  5283. /**
  5284. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5285. * Note : the vector "normal" is updated because normalized.
  5286. */
  5287. Plane.FromPositionAndNormal = function (origin, normal) {
  5288. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5289. normal.normalize();
  5290. result.normal = normal;
  5291. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5292. return result;
  5293. };
  5294. /**
  5295. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5296. */
  5297. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5298. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5299. return Vector3.Dot(point, normal) + d;
  5300. };
  5301. return Plane;
  5302. }());
  5303. BABYLON.Plane = Plane;
  5304. var Viewport = /** @class */ (function () {
  5305. /**
  5306. * Creates a Viewport object located at (x, y) and sized (width, height).
  5307. */
  5308. function Viewport(x, y, width, height) {
  5309. this.x = x;
  5310. this.y = y;
  5311. this.width = width;
  5312. this.height = height;
  5313. }
  5314. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5315. if (renderWidthOrEngine.getRenderWidth) {
  5316. var engine = renderWidthOrEngine;
  5317. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5318. }
  5319. var renderWidth = renderWidthOrEngine;
  5320. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5321. };
  5322. /**
  5323. * Returns a new Viewport copied from the current one.
  5324. */
  5325. Viewport.prototype.clone = function () {
  5326. return new Viewport(this.x, this.y, this.width, this.height);
  5327. };
  5328. return Viewport;
  5329. }());
  5330. BABYLON.Viewport = Viewport;
  5331. var Frustum = /** @class */ (function () {
  5332. function Frustum() {
  5333. }
  5334. /**
  5335. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5336. */
  5337. Frustum.GetPlanes = function (transform) {
  5338. var frustumPlanes = [];
  5339. for (var index = 0; index < 6; index++) {
  5340. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5341. }
  5342. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5343. return frustumPlanes;
  5344. };
  5345. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5346. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5347. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5348. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5349. frustumPlane.d = transform.m[15] + transform.m[14];
  5350. frustumPlane.normalize();
  5351. };
  5352. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5353. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5354. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5355. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5356. frustumPlane.d = transform.m[15] - transform.m[14];
  5357. frustumPlane.normalize();
  5358. };
  5359. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5360. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5361. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5362. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5363. frustumPlane.d = transform.m[15] + transform.m[12];
  5364. frustumPlane.normalize();
  5365. };
  5366. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5367. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5368. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5369. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5370. frustumPlane.d = transform.m[15] - transform.m[12];
  5371. frustumPlane.normalize();
  5372. };
  5373. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5374. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5375. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5376. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5377. frustumPlane.d = transform.m[15] - transform.m[13];
  5378. frustumPlane.normalize();
  5379. };
  5380. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5381. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5382. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5383. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5384. frustumPlane.d = transform.m[15] + transform.m[13];
  5385. frustumPlane.normalize();
  5386. };
  5387. /**
  5388. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5389. */
  5390. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5391. // Near
  5392. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5393. // Far
  5394. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5395. // Left
  5396. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5397. // Right
  5398. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5399. // Top
  5400. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5401. // Bottom
  5402. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5403. };
  5404. return Frustum;
  5405. }());
  5406. BABYLON.Frustum = Frustum;
  5407. var Space;
  5408. (function (Space) {
  5409. Space[Space["LOCAL"] = 0] = "LOCAL";
  5410. Space[Space["WORLD"] = 1] = "WORLD";
  5411. Space[Space["BONE"] = 2] = "BONE";
  5412. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5413. var Axis = /** @class */ (function () {
  5414. function Axis() {
  5415. }
  5416. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5417. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5418. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5419. return Axis;
  5420. }());
  5421. BABYLON.Axis = Axis;
  5422. ;
  5423. var BezierCurve = /** @class */ (function () {
  5424. function BezierCurve() {
  5425. }
  5426. /**
  5427. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5428. */
  5429. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5430. // Extract X (which is equal to time here)
  5431. var f0 = 1 - 3 * x2 + 3 * x1;
  5432. var f1 = 3 * x2 - 6 * x1;
  5433. var f2 = 3 * x1;
  5434. var refinedT = t;
  5435. for (var i = 0; i < 5; i++) {
  5436. var refinedT2 = refinedT * refinedT;
  5437. var refinedT3 = refinedT2 * refinedT;
  5438. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5439. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5440. refinedT -= (x - t) * slope;
  5441. refinedT = Math.min(1, Math.max(0, refinedT));
  5442. }
  5443. // Resolve cubic bezier for the given x
  5444. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5445. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5446. Math.pow(refinedT, 3);
  5447. };
  5448. return BezierCurve;
  5449. }());
  5450. BABYLON.BezierCurve = BezierCurve;
  5451. var Orientation;
  5452. (function (Orientation) {
  5453. Orientation[Orientation["CW"] = 0] = "CW";
  5454. Orientation[Orientation["CCW"] = 1] = "CCW";
  5455. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5456. var Angle = /** @class */ (function () {
  5457. /**
  5458. * Creates an Angle object of "radians" radians (float).
  5459. */
  5460. function Angle(radians) {
  5461. var _this = this;
  5462. /**
  5463. * Returns the Angle value in degrees (float).
  5464. */
  5465. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5466. /**
  5467. * Returns the Angle value in radians (float).
  5468. */
  5469. this.radians = function () { return _this._radians; };
  5470. this._radians = radians;
  5471. if (this._radians < 0.0)
  5472. this._radians += (2.0 * Math.PI);
  5473. }
  5474. /**
  5475. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5476. */
  5477. Angle.BetweenTwoPoints = function (a, b) {
  5478. var delta = b.subtract(a);
  5479. var theta = Math.atan2(delta.y, delta.x);
  5480. return new Angle(theta);
  5481. };
  5482. /**
  5483. * Returns a new Angle object from the passed float in radians.
  5484. */
  5485. Angle.FromRadians = function (radians) {
  5486. return new Angle(radians);
  5487. };
  5488. /**
  5489. * Returns a new Angle object from the passed float in degrees.
  5490. */
  5491. Angle.FromDegrees = function (degrees) {
  5492. return new Angle(degrees * Math.PI / 180.0);
  5493. };
  5494. return Angle;
  5495. }());
  5496. BABYLON.Angle = Angle;
  5497. var Arc2 = /** @class */ (function () {
  5498. /**
  5499. * Creates an Arc object from the three passed points : start, middle and end.
  5500. */
  5501. function Arc2(startPoint, midPoint, endPoint) {
  5502. this.startPoint = startPoint;
  5503. this.midPoint = midPoint;
  5504. this.endPoint = endPoint;
  5505. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5506. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5507. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5508. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5509. 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);
  5510. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5511. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5512. var a1 = this.startAngle.degrees();
  5513. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5514. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5515. // angles correction
  5516. if (a2 - a1 > +180.0)
  5517. a2 -= 360.0;
  5518. if (a2 - a1 < -180.0)
  5519. a2 += 360.0;
  5520. if (a3 - a2 > +180.0)
  5521. a3 -= 360.0;
  5522. if (a3 - a2 < -180.0)
  5523. a3 += 360.0;
  5524. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5525. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5526. }
  5527. return Arc2;
  5528. }());
  5529. BABYLON.Arc2 = Arc2;
  5530. var Path2 = /** @class */ (function () {
  5531. /**
  5532. * Creates a Path2 object from the starting 2D coordinates x and y.
  5533. */
  5534. function Path2(x, y) {
  5535. this._points = new Array();
  5536. this._length = 0.0;
  5537. this.closed = false;
  5538. this._points.push(new Vector2(x, y));
  5539. }
  5540. /**
  5541. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5542. * Returns the updated Path2.
  5543. */
  5544. Path2.prototype.addLineTo = function (x, y) {
  5545. if (this.closed) {
  5546. //Tools.Error("cannot add lines to closed paths");
  5547. return this;
  5548. }
  5549. var newPoint = new Vector2(x, y);
  5550. var previousPoint = this._points[this._points.length - 1];
  5551. this._points.push(newPoint);
  5552. this._length += newPoint.subtract(previousPoint).length();
  5553. return this;
  5554. };
  5555. /**
  5556. * 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.
  5557. * Returns the updated Path2.
  5558. */
  5559. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5560. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5561. if (this.closed) {
  5562. //Tools.Error("cannot add arcs to closed paths");
  5563. return this;
  5564. }
  5565. var startPoint = this._points[this._points.length - 1];
  5566. var midPoint = new Vector2(midX, midY);
  5567. var endPoint = new Vector2(endX, endY);
  5568. var arc = new Arc2(startPoint, midPoint, endPoint);
  5569. var increment = arc.angle.radians() / numberOfSegments;
  5570. if (arc.orientation === Orientation.CW)
  5571. increment *= -1;
  5572. var currentAngle = arc.startAngle.radians() + increment;
  5573. for (var i = 0; i < numberOfSegments; i++) {
  5574. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5575. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5576. this.addLineTo(x, y);
  5577. currentAngle += increment;
  5578. }
  5579. return this;
  5580. };
  5581. /**
  5582. * Closes the Path2.
  5583. * Returns the Path2.
  5584. */
  5585. Path2.prototype.close = function () {
  5586. this.closed = true;
  5587. return this;
  5588. };
  5589. /**
  5590. * Returns the Path2 total length (float).
  5591. */
  5592. Path2.prototype.length = function () {
  5593. var result = this._length;
  5594. if (!this.closed) {
  5595. var lastPoint = this._points[this._points.length - 1];
  5596. var firstPoint = this._points[0];
  5597. result += (firstPoint.subtract(lastPoint).length());
  5598. }
  5599. return result;
  5600. };
  5601. /**
  5602. * Returns the Path2 internal array of points.
  5603. */
  5604. Path2.prototype.getPoints = function () {
  5605. return this._points;
  5606. };
  5607. /**
  5608. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5609. */
  5610. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5611. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5612. //Tools.Error("normalized length position should be between 0 and 1.");
  5613. return Vector2.Zero();
  5614. }
  5615. var lengthPosition = normalizedLengthPosition * this.length();
  5616. var previousOffset = 0;
  5617. for (var i = 0; i < this._points.length; i++) {
  5618. var j = (i + 1) % this._points.length;
  5619. var a = this._points[i];
  5620. var b = this._points[j];
  5621. var bToA = b.subtract(a);
  5622. var nextOffset = (bToA.length() + previousOffset);
  5623. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5624. var dir = bToA.normalize();
  5625. var localOffset = lengthPosition - previousOffset;
  5626. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5627. }
  5628. previousOffset = nextOffset;
  5629. }
  5630. //Tools.Error("internal error");
  5631. return Vector2.Zero();
  5632. };
  5633. /**
  5634. * Returns a new Path2 starting at the coordinates (x, y).
  5635. */
  5636. Path2.StartingAt = function (x, y) {
  5637. return new Path2(x, y);
  5638. };
  5639. return Path2;
  5640. }());
  5641. BABYLON.Path2 = Path2;
  5642. var Path3D = /** @class */ (function () {
  5643. /**
  5644. * new Path3D(path, normal, raw)
  5645. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5646. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5647. * path : an array of Vector3, the curve axis of the Path3D
  5648. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5649. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5650. */
  5651. function Path3D(path, firstNormal, raw) {
  5652. if (firstNormal === void 0) { firstNormal = null; }
  5653. this.path = path;
  5654. this._curve = new Array();
  5655. this._distances = new Array();
  5656. this._tangents = new Array();
  5657. this._normals = new Array();
  5658. this._binormals = new Array();
  5659. for (var p = 0; p < path.length; p++) {
  5660. this._curve[p] = path[p].clone(); // hard copy
  5661. }
  5662. this._raw = raw || false;
  5663. this._compute(firstNormal);
  5664. }
  5665. /**
  5666. * Returns the Path3D array of successive Vector3 designing its curve.
  5667. */
  5668. Path3D.prototype.getCurve = function () {
  5669. return this._curve;
  5670. };
  5671. /**
  5672. * Returns an array populated with tangent vectors on each Path3D curve point.
  5673. */
  5674. Path3D.prototype.getTangents = function () {
  5675. return this._tangents;
  5676. };
  5677. /**
  5678. * Returns an array populated with normal vectors on each Path3D curve point.
  5679. */
  5680. Path3D.prototype.getNormals = function () {
  5681. return this._normals;
  5682. };
  5683. /**
  5684. * Returns an array populated with binormal vectors on each Path3D curve point.
  5685. */
  5686. Path3D.prototype.getBinormals = function () {
  5687. return this._binormals;
  5688. };
  5689. /**
  5690. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5691. */
  5692. Path3D.prototype.getDistances = function () {
  5693. return this._distances;
  5694. };
  5695. /**
  5696. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5697. * Returns the same object updated.
  5698. */
  5699. Path3D.prototype.update = function (path, firstNormal) {
  5700. if (firstNormal === void 0) { firstNormal = null; }
  5701. for (var p = 0; p < path.length; p++) {
  5702. this._curve[p].x = path[p].x;
  5703. this._curve[p].y = path[p].y;
  5704. this._curve[p].z = path[p].z;
  5705. }
  5706. this._compute(firstNormal);
  5707. return this;
  5708. };
  5709. // private function compute() : computes tangents, normals and binormals
  5710. Path3D.prototype._compute = function (firstNormal) {
  5711. var l = this._curve.length;
  5712. // first and last tangents
  5713. this._tangents[0] = this._getFirstNonNullVector(0);
  5714. if (!this._raw) {
  5715. this._tangents[0].normalize();
  5716. }
  5717. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5718. if (!this._raw) {
  5719. this._tangents[l - 1].normalize();
  5720. }
  5721. // normals and binormals at first point : arbitrary vector with _normalVector()
  5722. var tg0 = this._tangents[0];
  5723. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5724. this._normals[0] = pp0;
  5725. if (!this._raw) {
  5726. this._normals[0].normalize();
  5727. }
  5728. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5729. if (!this._raw) {
  5730. this._binormals[0].normalize();
  5731. }
  5732. this._distances[0] = 0.0;
  5733. // normals and binormals : next points
  5734. var prev; // previous vector (segment)
  5735. var cur; // current vector (segment)
  5736. var curTang; // current tangent
  5737. // previous normal
  5738. var prevBinor; // previous binormal
  5739. for (var i = 1; i < l; i++) {
  5740. // tangents
  5741. prev = this._getLastNonNullVector(i);
  5742. if (i < l - 1) {
  5743. cur = this._getFirstNonNullVector(i);
  5744. this._tangents[i] = prev.add(cur);
  5745. this._tangents[i].normalize();
  5746. }
  5747. this._distances[i] = this._distances[i - 1] + prev.length();
  5748. // normals and binormals
  5749. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5750. curTang = this._tangents[i];
  5751. prevBinor = this._binormals[i - 1];
  5752. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5753. if (!this._raw) {
  5754. this._normals[i].normalize();
  5755. }
  5756. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5757. if (!this._raw) {
  5758. this._binormals[i].normalize();
  5759. }
  5760. }
  5761. };
  5762. // private function getFirstNonNullVector(index)
  5763. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5764. Path3D.prototype._getFirstNonNullVector = function (index) {
  5765. var i = 1;
  5766. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5767. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5768. i++;
  5769. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5770. }
  5771. return nNVector;
  5772. };
  5773. // private function getLastNonNullVector(index)
  5774. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5775. Path3D.prototype._getLastNonNullVector = function (index) {
  5776. var i = 1;
  5777. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5778. while (nLVector.length() === 0 && index > i + 1) {
  5779. i++;
  5780. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5781. }
  5782. return nLVector;
  5783. };
  5784. // private function normalVector(v0, vt, va) :
  5785. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5786. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5787. Path3D.prototype._normalVector = function (v0, vt, va) {
  5788. var normal0;
  5789. var tgl = vt.length();
  5790. if (tgl === 0.0) {
  5791. tgl = 1.0;
  5792. }
  5793. if (va === undefined || va === null) {
  5794. var point;
  5795. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5796. point = new Vector3(0.0, -1.0, 0.0);
  5797. }
  5798. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5799. point = new Vector3(1.0, 0.0, 0.0);
  5800. }
  5801. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5802. point = new Vector3(0.0, 0.0, 1.0);
  5803. }
  5804. else {
  5805. point = Vector3.Zero();
  5806. }
  5807. normal0 = Vector3.Cross(vt, point);
  5808. }
  5809. else {
  5810. normal0 = Vector3.Cross(vt, va);
  5811. Vector3.CrossToRef(normal0, vt, normal0);
  5812. }
  5813. normal0.normalize();
  5814. return normal0;
  5815. };
  5816. return Path3D;
  5817. }());
  5818. BABYLON.Path3D = Path3D;
  5819. var Curve3 = /** @class */ (function () {
  5820. /**
  5821. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5822. * A Curve3 is designed from a series of successive Vector3.
  5823. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5824. */
  5825. function Curve3(points) {
  5826. this._length = 0.0;
  5827. this._points = points;
  5828. this._length = this._computeLength(points);
  5829. }
  5830. /**
  5831. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5832. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5833. * @param v1 (Vector3) the control point
  5834. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5835. * @param nbPoints (integer) the wanted number of points in the curve
  5836. */
  5837. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5838. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5839. var bez = new Array();
  5840. var equation = function (t, val0, val1, val2) {
  5841. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5842. return res;
  5843. };
  5844. for (var i = 0; i <= nbPoints; i++) {
  5845. 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)));
  5846. }
  5847. return new Curve3(bez);
  5848. };
  5849. /**
  5850. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5851. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5852. * @param v1 (Vector3) the first control point
  5853. * @param v2 (Vector3) the second control point
  5854. * @param v3 (Vector3) the end point of the Cubic Bezier
  5855. * @param nbPoints (integer) the wanted number of points in the curve
  5856. */
  5857. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5858. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5859. var bez = new Array();
  5860. var equation = function (t, val0, val1, val2, val3) {
  5861. 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;
  5862. return res;
  5863. };
  5864. for (var i = 0; i <= nbPoints; i++) {
  5865. 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)));
  5866. }
  5867. return new Curve3(bez);
  5868. };
  5869. /**
  5870. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5871. * @param p1 (Vector3) the origin point of the Hermite Spline
  5872. * @param t1 (Vector3) the tangent vector at the origin point
  5873. * @param p2 (Vector3) the end point of the Hermite Spline
  5874. * @param t2 (Vector3) the tangent vector at the end point
  5875. * @param nbPoints (integer) the wanted number of points in the curve
  5876. */
  5877. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5878. var hermite = new Array();
  5879. var step = 1.0 / nbPoints;
  5880. for (var i = 0; i <= nbPoints; i++) {
  5881. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5882. }
  5883. return new Curve3(hermite);
  5884. };
  5885. /**
  5886. * Returns a Curve3 object along a CatmullRom Spline curve :
  5887. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5888. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5889. */
  5890. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5891. var totalPoints = new Array();
  5892. totalPoints.push(points[0].clone());
  5893. Array.prototype.push.apply(totalPoints, points);
  5894. totalPoints.push(points[points.length - 1].clone());
  5895. var catmullRom = new Array();
  5896. var step = 1.0 / nbPoints;
  5897. var amount = 0.0;
  5898. for (var i = 0; i < totalPoints.length - 3; i++) {
  5899. amount = 0;
  5900. for (var c = 0; c < nbPoints; c++) {
  5901. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5902. amount += step;
  5903. }
  5904. }
  5905. i--;
  5906. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5907. return new Curve3(catmullRom);
  5908. };
  5909. /**
  5910. * Returns the Curve3 stored array of successive Vector3
  5911. */
  5912. Curve3.prototype.getPoints = function () {
  5913. return this._points;
  5914. };
  5915. /**
  5916. * Returns the computed length (float) of the curve.
  5917. */
  5918. Curve3.prototype.length = function () {
  5919. return this._length;
  5920. };
  5921. /**
  5922. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5923. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5924. * curveA and curveB keep unchanged.
  5925. */
  5926. Curve3.prototype.continue = function (curve) {
  5927. var lastPoint = this._points[this._points.length - 1];
  5928. var continuedPoints = this._points.slice();
  5929. var curvePoints = curve.getPoints();
  5930. for (var i = 1; i < curvePoints.length; i++) {
  5931. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5932. }
  5933. var continuedCurve = new Curve3(continuedPoints);
  5934. return continuedCurve;
  5935. };
  5936. Curve3.prototype._computeLength = function (path) {
  5937. var l = 0;
  5938. for (var i = 1; i < path.length; i++) {
  5939. l += (path[i].subtract(path[i - 1])).length();
  5940. }
  5941. return l;
  5942. };
  5943. return Curve3;
  5944. }());
  5945. BABYLON.Curve3 = Curve3;
  5946. // Vertex formats
  5947. var PositionNormalVertex = /** @class */ (function () {
  5948. function PositionNormalVertex(position, normal) {
  5949. if (position === void 0) { position = Vector3.Zero(); }
  5950. if (normal === void 0) { normal = Vector3.Up(); }
  5951. this.position = position;
  5952. this.normal = normal;
  5953. }
  5954. PositionNormalVertex.prototype.clone = function () {
  5955. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5956. };
  5957. return PositionNormalVertex;
  5958. }());
  5959. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5960. var PositionNormalTextureVertex = /** @class */ (function () {
  5961. function PositionNormalTextureVertex(position, normal, uv) {
  5962. if (position === void 0) { position = Vector3.Zero(); }
  5963. if (normal === void 0) { normal = Vector3.Up(); }
  5964. if (uv === void 0) { uv = Vector2.Zero(); }
  5965. this.position = position;
  5966. this.normal = normal;
  5967. this.uv = uv;
  5968. }
  5969. PositionNormalTextureVertex.prototype.clone = function () {
  5970. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5971. };
  5972. return PositionNormalTextureVertex;
  5973. }());
  5974. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5975. // Temporary pre-allocated objects for engine internal use
  5976. // usage in any internal function :
  5977. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5978. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5979. var Tmp = /** @class */ (function () {
  5980. function Tmp() {
  5981. }
  5982. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5983. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5984. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5985. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5986. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5987. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5988. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5989. Matrix.Zero(), Matrix.Zero(),
  5990. Matrix.Zero(), Matrix.Zero(),
  5991. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5992. return Tmp;
  5993. }());
  5994. BABYLON.Tmp = Tmp;
  5995. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5996. var MathTmp = /** @class */ (function () {
  5997. function MathTmp() {
  5998. }
  5999. MathTmp.Vector3 = [Vector3.Zero()];
  6000. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6001. MathTmp.Quaternion = [Quaternion.Zero()];
  6002. return MathTmp;
  6003. }());
  6004. })(BABYLON || (BABYLON = {}));
  6005. //# sourceMappingURL=babylon.math.js.map
  6006. var BABYLON;
  6007. (function (BABYLON) {
  6008. var Scalar = /** @class */ (function () {
  6009. function Scalar() {
  6010. }
  6011. /**
  6012. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6013. */
  6014. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6015. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6016. var num = a - b;
  6017. return -epsilon <= num && num <= epsilon;
  6018. };
  6019. /**
  6020. * Returns a string : the upper case translation of the number i to hexadecimal.
  6021. */
  6022. Scalar.ToHex = function (i) {
  6023. var str = i.toString(16);
  6024. if (i <= 15) {
  6025. return ("0" + str).toUpperCase();
  6026. }
  6027. return str.toUpperCase();
  6028. };
  6029. /**
  6030. * Returns -1 if value is negative and +1 is value is positive.
  6031. * Returns the value itself if it's equal to zero.
  6032. */
  6033. Scalar.Sign = function (value) {
  6034. value = +value; // convert to a number
  6035. if (value === 0 || isNaN(value))
  6036. return value;
  6037. return value > 0 ? 1 : -1;
  6038. };
  6039. /**
  6040. * Returns the value itself if it's between min and max.
  6041. * Returns min if the value is lower than min.
  6042. * Returns max if the value is greater than max.
  6043. */
  6044. Scalar.Clamp = function (value, min, max) {
  6045. if (min === void 0) { min = 0; }
  6046. if (max === void 0) { max = 1; }
  6047. return Math.min(max, Math.max(min, value));
  6048. };
  6049. /**
  6050. * Returns the log2 of value.
  6051. */
  6052. Scalar.Log2 = function (value) {
  6053. return Math.log(value) * Math.LOG2E;
  6054. };
  6055. /**
  6056. * Loops the value, so that it is never larger than length and never smaller than 0.
  6057. *
  6058. * This is similar to the modulo operator but it works with floating point numbers.
  6059. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6060. * With t = 5 and length = 2.5, the result would be 0.0.
  6061. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6062. */
  6063. Scalar.Repeat = function (value, length) {
  6064. return value - Math.floor(value / length) * length;
  6065. };
  6066. /**
  6067. * Normalize the value between 0.0 and 1.0 using min and max values
  6068. */
  6069. Scalar.Normalize = function (value, min, max) {
  6070. return (value - min) / (max - min);
  6071. };
  6072. /**
  6073. * Denormalize the value from 0.0 and 1.0 using min and max values
  6074. */
  6075. Scalar.Denormalize = function (normalized, min, max) {
  6076. return (normalized * (max - min) + min);
  6077. };
  6078. /**
  6079. * Calculates the shortest difference between two given angles given in degrees.
  6080. */
  6081. Scalar.DeltaAngle = function (current, target) {
  6082. var num = Scalar.Repeat(target - current, 360.0);
  6083. if (num > 180.0) {
  6084. num -= 360.0;
  6085. }
  6086. return num;
  6087. };
  6088. /**
  6089. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6090. *
  6091. * The returned value will move back and forth between 0 and length
  6092. */
  6093. Scalar.PingPong = function (tx, length) {
  6094. var t = Scalar.Repeat(tx, length * 2.0);
  6095. return length - Math.abs(t - length);
  6096. };
  6097. /**
  6098. * Interpolates between min and max with smoothing at the limits.
  6099. *
  6100. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6101. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6102. */
  6103. Scalar.SmoothStep = function (from, to, tx) {
  6104. var t = Scalar.Clamp(tx);
  6105. t = -2.0 * t * t * t + 3.0 * t * t;
  6106. return to * t + from * (1.0 - t);
  6107. };
  6108. /**
  6109. * Moves a value current towards target.
  6110. *
  6111. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6112. * Negative values of maxDelta pushes the value away from target.
  6113. */
  6114. Scalar.MoveTowards = function (current, target, maxDelta) {
  6115. var result = 0;
  6116. if (Math.abs(target - current) <= maxDelta) {
  6117. result = target;
  6118. }
  6119. else {
  6120. result = current + Scalar.Sign(target - current) * maxDelta;
  6121. }
  6122. return result;
  6123. };
  6124. /**
  6125. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6126. *
  6127. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6128. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6129. */
  6130. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6131. var num = Scalar.DeltaAngle(current, target);
  6132. var result = 0;
  6133. if (-maxDelta < num && num < maxDelta) {
  6134. result = target;
  6135. }
  6136. else {
  6137. target = current + num;
  6138. result = Scalar.MoveTowards(current, target, maxDelta);
  6139. }
  6140. return result;
  6141. };
  6142. /**
  6143. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6144. */
  6145. Scalar.Lerp = function (start, end, amount) {
  6146. return start + ((end - start) * amount);
  6147. };
  6148. /**
  6149. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6150. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6151. */
  6152. Scalar.LerpAngle = function (start, end, amount) {
  6153. var num = Scalar.Repeat(end - start, 360.0);
  6154. if (num > 180.0) {
  6155. num -= 360.0;
  6156. }
  6157. return start + num * Scalar.Clamp(amount);
  6158. };
  6159. /**
  6160. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6161. */
  6162. Scalar.InverseLerp = function (a, b, value) {
  6163. var result = 0;
  6164. if (a != b) {
  6165. result = Scalar.Clamp((value - a) / (b - a));
  6166. }
  6167. else {
  6168. result = 0.0;
  6169. }
  6170. return result;
  6171. };
  6172. /**
  6173. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6174. */
  6175. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6176. var squared = amount * amount;
  6177. var cubed = amount * squared;
  6178. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6179. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6180. var part3 = (cubed - (2.0 * squared)) + amount;
  6181. var part4 = cubed - squared;
  6182. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6183. };
  6184. /**
  6185. * Returns a random float number between and min and max values
  6186. */
  6187. Scalar.RandomRange = function (min, max) {
  6188. if (min === max)
  6189. return min;
  6190. return ((Math.random() * (max - min)) + min);
  6191. };
  6192. /**
  6193. * This function returns percentage of a number in a given range.
  6194. *
  6195. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6196. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6197. */
  6198. Scalar.RangeToPercent = function (number, min, max) {
  6199. return ((number - min) / (max - min));
  6200. };
  6201. /**
  6202. * This function returns number that corresponds to the percentage in a given range.
  6203. *
  6204. * PercentToRange(0.34,0,100) will return 34.
  6205. */
  6206. Scalar.PercentToRange = function (percent, min, max) {
  6207. return ((max - min) * percent + min);
  6208. };
  6209. /**
  6210. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6211. * @param angle The angle to normalize in radian.
  6212. * @return The converted angle.
  6213. */
  6214. Scalar.NormalizeRadians = function (angle) {
  6215. // More precise but slower version kept for reference.
  6216. // angle = angle % Tools.TwoPi;
  6217. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6218. //if (angle > Math.PI) {
  6219. // angle -= Tools.TwoPi;
  6220. //}
  6221. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6222. return angle;
  6223. };
  6224. /**
  6225. * Two pi constants convenient for computation.
  6226. */
  6227. Scalar.TwoPi = Math.PI * 2;
  6228. return Scalar;
  6229. }());
  6230. BABYLON.Scalar = Scalar;
  6231. })(BABYLON || (BABYLON = {}));
  6232. //# sourceMappingURL=babylon.math.scalar.js.map
  6233. //# sourceMappingURL=babylon.mixins.js.map
  6234. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6235. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6236. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6237. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6238. //# sourceMappingURL=babylon.webgl2.js.map
  6239. var BABYLON;
  6240. (function (BABYLON) {
  6241. var __decoratorInitialStore = {};
  6242. var __mergedStore = {};
  6243. var _copySource = function (creationFunction, source, instanciate) {
  6244. var destination = creationFunction();
  6245. // Tags
  6246. if (BABYLON.Tags) {
  6247. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6248. }
  6249. var classStore = getMergedStore(destination);
  6250. // Properties
  6251. for (var property in classStore) {
  6252. var propertyDescriptor = classStore[property];
  6253. var sourceProperty = source[property];
  6254. var propertyType = propertyDescriptor.type;
  6255. if (sourceProperty !== undefined && sourceProperty !== null) {
  6256. switch (propertyType) {
  6257. case 0: // Value
  6258. case 6:// Mesh reference
  6259. destination[property] = sourceProperty;
  6260. break;
  6261. case 1:// Texture
  6262. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6263. break;
  6264. case 2: // Color3
  6265. case 3: // FresnelParameters
  6266. case 4: // Vector2
  6267. case 5: // Vector3
  6268. case 7: // Color Curves
  6269. case 10:// Quaternion
  6270. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6271. break;
  6272. }
  6273. }
  6274. }
  6275. return destination;
  6276. };
  6277. function getDirectStore(target) {
  6278. var classKey = target.getClassName();
  6279. if (!__decoratorInitialStore[classKey]) {
  6280. __decoratorInitialStore[classKey] = {};
  6281. }
  6282. return __decoratorInitialStore[classKey];
  6283. }
  6284. /**
  6285. * Return the list of properties flagged as serializable
  6286. * @param target: host object
  6287. */
  6288. function getMergedStore(target) {
  6289. var classKey = target.getClassName();
  6290. if (__mergedStore[classKey]) {
  6291. return __mergedStore[classKey];
  6292. }
  6293. __mergedStore[classKey] = {};
  6294. var store = __mergedStore[classKey];
  6295. var currentTarget = target;
  6296. var currentKey = classKey;
  6297. while (currentKey) {
  6298. var initialStore = __decoratorInitialStore[currentKey];
  6299. for (var property in initialStore) {
  6300. store[property] = initialStore[property];
  6301. }
  6302. var parent_1 = void 0;
  6303. var done = false;
  6304. do {
  6305. parent_1 = Object.getPrototypeOf(currentTarget);
  6306. if (!parent_1.getClassName) {
  6307. done = true;
  6308. break;
  6309. }
  6310. if (parent_1.getClassName() !== currentKey) {
  6311. break;
  6312. }
  6313. currentTarget = parent_1;
  6314. } while (parent_1);
  6315. if (done) {
  6316. break;
  6317. }
  6318. currentKey = parent_1.getClassName();
  6319. currentTarget = parent_1;
  6320. }
  6321. return store;
  6322. }
  6323. function generateSerializableMember(type, sourceName) {
  6324. return function (target, propertyKey) {
  6325. var classStore = getDirectStore(target);
  6326. if (!classStore[propertyKey]) {
  6327. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6328. }
  6329. };
  6330. }
  6331. function generateExpandMember(setCallback, targetKey) {
  6332. if (targetKey === void 0) { targetKey = null; }
  6333. return function (target, propertyKey) {
  6334. var key = targetKey || ("_" + propertyKey);
  6335. Object.defineProperty(target, propertyKey, {
  6336. get: function () {
  6337. return this[key];
  6338. },
  6339. set: function (value) {
  6340. if (this[key] === value) {
  6341. return;
  6342. }
  6343. this[key] = value;
  6344. target[setCallback].apply(this);
  6345. },
  6346. enumerable: true,
  6347. configurable: true
  6348. });
  6349. };
  6350. }
  6351. function expandToProperty(callback, targetKey) {
  6352. if (targetKey === void 0) { targetKey = null; }
  6353. return generateExpandMember(callback, targetKey);
  6354. }
  6355. BABYLON.expandToProperty = expandToProperty;
  6356. function serialize(sourceName) {
  6357. return generateSerializableMember(0, sourceName); // value member
  6358. }
  6359. BABYLON.serialize = serialize;
  6360. function serializeAsTexture(sourceName) {
  6361. return generateSerializableMember(1, sourceName); // texture member
  6362. }
  6363. BABYLON.serializeAsTexture = serializeAsTexture;
  6364. function serializeAsColor3(sourceName) {
  6365. return generateSerializableMember(2, sourceName); // color3 member
  6366. }
  6367. BABYLON.serializeAsColor3 = serializeAsColor3;
  6368. function serializeAsFresnelParameters(sourceName) {
  6369. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6370. }
  6371. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6372. function serializeAsVector2(sourceName) {
  6373. return generateSerializableMember(4, sourceName); // vector2 member
  6374. }
  6375. BABYLON.serializeAsVector2 = serializeAsVector2;
  6376. function serializeAsVector3(sourceName) {
  6377. return generateSerializableMember(5, sourceName); // vector3 member
  6378. }
  6379. BABYLON.serializeAsVector3 = serializeAsVector3;
  6380. function serializeAsMeshReference(sourceName) {
  6381. return generateSerializableMember(6, sourceName); // mesh reference member
  6382. }
  6383. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6384. function serializeAsColorCurves(sourceName) {
  6385. return generateSerializableMember(7, sourceName); // color curves
  6386. }
  6387. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6388. function serializeAsColor4(sourceName) {
  6389. return generateSerializableMember(8, sourceName); // color 4
  6390. }
  6391. BABYLON.serializeAsColor4 = serializeAsColor4;
  6392. function serializeAsImageProcessingConfiguration(sourceName) {
  6393. return generateSerializableMember(9, sourceName); // image processing
  6394. }
  6395. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6396. function serializeAsQuaternion(sourceName) {
  6397. return generateSerializableMember(10, sourceName); // quaternion member
  6398. }
  6399. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6400. var SerializationHelper = /** @class */ (function () {
  6401. function SerializationHelper() {
  6402. }
  6403. SerializationHelper.Serialize = function (entity, serializationObject) {
  6404. if (!serializationObject) {
  6405. serializationObject = {};
  6406. }
  6407. // Tags
  6408. if (BABYLON.Tags) {
  6409. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6410. }
  6411. var serializedProperties = getMergedStore(entity);
  6412. // Properties
  6413. for (var property in serializedProperties) {
  6414. var propertyDescriptor = serializedProperties[property];
  6415. var targetPropertyName = propertyDescriptor.sourceName || property;
  6416. var propertyType = propertyDescriptor.type;
  6417. var sourceProperty = entity[property];
  6418. if (sourceProperty !== undefined && sourceProperty !== null) {
  6419. switch (propertyType) {
  6420. case 0:// Value
  6421. serializationObject[targetPropertyName] = sourceProperty;
  6422. break;
  6423. case 1:// Texture
  6424. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6425. break;
  6426. case 2:// Color3
  6427. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6428. break;
  6429. case 3:// FresnelParameters
  6430. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6431. break;
  6432. case 4:// Vector2
  6433. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6434. break;
  6435. case 5:// Vector3
  6436. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6437. break;
  6438. case 6:// Mesh reference
  6439. serializationObject[targetPropertyName] = sourceProperty.id;
  6440. break;
  6441. case 7:// Color Curves
  6442. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6443. break;
  6444. case 8:// Color 4
  6445. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6446. break;
  6447. case 9:// Image Processing
  6448. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6449. break;
  6450. }
  6451. }
  6452. }
  6453. return serializationObject;
  6454. };
  6455. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6456. if (rootUrl === void 0) { rootUrl = null; }
  6457. var destination = creationFunction();
  6458. if (!rootUrl) {
  6459. rootUrl = "";
  6460. }
  6461. // Tags
  6462. if (BABYLON.Tags) {
  6463. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6464. }
  6465. var classStore = getMergedStore(destination);
  6466. // Properties
  6467. for (var property in classStore) {
  6468. var propertyDescriptor = classStore[property];
  6469. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6470. var propertyType = propertyDescriptor.type;
  6471. if (sourceProperty !== undefined && sourceProperty !== null) {
  6472. var dest = destination;
  6473. switch (propertyType) {
  6474. case 0:// Value
  6475. dest[property] = sourceProperty;
  6476. break;
  6477. case 1:// Texture
  6478. if (scene) {
  6479. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6480. }
  6481. break;
  6482. case 2:// Color3
  6483. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6484. break;
  6485. case 3:// FresnelParameters
  6486. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6487. break;
  6488. case 4:// Vector2
  6489. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6490. break;
  6491. case 5:// Vector3
  6492. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6493. break;
  6494. case 6:// Mesh reference
  6495. if (scene) {
  6496. dest[property] = scene.getLastMeshByID(sourceProperty);
  6497. }
  6498. break;
  6499. case 7:// Color Curves
  6500. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6501. break;
  6502. case 8:// Color 4
  6503. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6504. break;
  6505. case 9:// Image Processing
  6506. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6507. break;
  6508. }
  6509. }
  6510. }
  6511. return destination;
  6512. };
  6513. SerializationHelper.Clone = function (creationFunction, source) {
  6514. return _copySource(creationFunction, source, false);
  6515. };
  6516. SerializationHelper.Instanciate = function (creationFunction, source) {
  6517. return _copySource(creationFunction, source, true);
  6518. };
  6519. return SerializationHelper;
  6520. }());
  6521. BABYLON.SerializationHelper = SerializationHelper;
  6522. })(BABYLON || (BABYLON = {}));
  6523. //# sourceMappingURL=babylon.decorators.js.map
  6524. var BABYLON;
  6525. (function (BABYLON) {
  6526. /**
  6527. * A class serves as a medium between the observable and its observers
  6528. */
  6529. var EventState = /** @class */ (function () {
  6530. /**
  6531. * Create a new EventState
  6532. * @param mask defines the mask associated with this state
  6533. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  6534. * @param target defines the original target of the state
  6535. * @param currentTarget defines the current target of the state
  6536. */
  6537. function EventState(mask, skipNextObservers, target, currentTarget) {
  6538. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6539. this.initalize(mask, skipNextObservers, target, currentTarget);
  6540. }
  6541. /**
  6542. * Initialize the current event state
  6543. * @param mask defines the mask associated with this state
  6544. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  6545. * @param target defines the original target of the state
  6546. * @param currentTarget defines the current target of the state
  6547. * @returns the current event state
  6548. */
  6549. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6550. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6551. this.mask = mask;
  6552. this.skipNextObservers = skipNextObservers;
  6553. this.target = target;
  6554. this.currentTarget = currentTarget;
  6555. return this;
  6556. };
  6557. return EventState;
  6558. }());
  6559. BABYLON.EventState = EventState;
  6560. /**
  6561. * Represent an Observer registered to a given Observable object.
  6562. */
  6563. var Observer = /** @class */ (function () {
  6564. /**
  6565. * Creates a new observer
  6566. * @param callback defines the callback to call when the observer is notified
  6567. * @param mask defines the mask of the observer (used to filter notifications)
  6568. * @param scope defines the current scope used to restore the JS context
  6569. */
  6570. function Observer(
  6571. /**
  6572. * Defines the callback to call when the observer is notified
  6573. */
  6574. callback,
  6575. /**
  6576. * Defines the mask of the observer (used to filter notifications)
  6577. */
  6578. mask,
  6579. /**
  6580. * Defines the current scope used to restore the JS context
  6581. */
  6582. scope) {
  6583. if (scope === void 0) { scope = null; }
  6584. this.callback = callback;
  6585. this.mask = mask;
  6586. this.scope = scope;
  6587. /**
  6588. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  6589. */
  6590. this.unregisterOnNextCall = false;
  6591. }
  6592. return Observer;
  6593. }());
  6594. BABYLON.Observer = Observer;
  6595. /**
  6596. * Represent a list of observers registered to multiple Observables object.
  6597. */
  6598. var MultiObserver = /** @class */ (function () {
  6599. function MultiObserver() {
  6600. }
  6601. /**
  6602. * Release associated resources
  6603. */
  6604. MultiObserver.prototype.dispose = function () {
  6605. if (this._observers && this._observables) {
  6606. for (var index = 0; index < this._observers.length; index++) {
  6607. this._observables[index].remove(this._observers[index]);
  6608. }
  6609. }
  6610. this._observers = null;
  6611. this._observables = null;
  6612. };
  6613. /**
  6614. * Raise a callback when one of the observable will notify
  6615. * @param observables defines a list of observables to watch
  6616. * @param callback defines the callback to call on notification
  6617. * @param mask defines the mask used to filter notifications
  6618. * @param scope defines the current scope used to restore the JS context
  6619. * @returns the new MultiObserver
  6620. */
  6621. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6622. if (mask === void 0) { mask = -1; }
  6623. if (scope === void 0) { scope = null; }
  6624. var result = new MultiObserver();
  6625. result._observers = new Array();
  6626. result._observables = observables;
  6627. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6628. var observable = observables_1[_i];
  6629. var observer = observable.add(callback, mask, false, scope);
  6630. if (observer) {
  6631. result._observers.push(observer);
  6632. }
  6633. }
  6634. return result;
  6635. };
  6636. return MultiObserver;
  6637. }());
  6638. BABYLON.MultiObserver = MultiObserver;
  6639. /**
  6640. * The Observable class is a simple implementation of the Observable pattern.
  6641. * 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.
  6642. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6643. * 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).
  6644. * 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.
  6645. */
  6646. var Observable = /** @class */ (function () {
  6647. /**
  6648. * Creates a new observable
  6649. * @param onObserverAdded defines a callback to call when a new observer is added
  6650. */
  6651. function Observable(onObserverAdded) {
  6652. this._observers = new Array();
  6653. this._eventState = new EventState(0);
  6654. if (onObserverAdded) {
  6655. this._onObserverAdded = onObserverAdded;
  6656. }
  6657. }
  6658. /**
  6659. * Create a new Observer with the specified callback
  6660. * @param callback the callback that will be executed for that Observer
  6661. * @param mask the mask used to filter observers
  6662. * @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.
  6663. * @param scope optional scope for the callback to be called from
  6664. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  6665. * @returns the new observer created for the callback
  6666. */
  6667. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  6668. if (mask === void 0) { mask = -1; }
  6669. if (insertFirst === void 0) { insertFirst = false; }
  6670. if (scope === void 0) { scope = null; }
  6671. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  6672. if (!callback) {
  6673. return null;
  6674. }
  6675. var observer = new Observer(callback, mask, scope);
  6676. observer.unregisterOnNextCall = unregisterOnFirstCall;
  6677. if (insertFirst) {
  6678. this._observers.unshift(observer);
  6679. }
  6680. else {
  6681. this._observers.push(observer);
  6682. }
  6683. if (this._onObserverAdded) {
  6684. this._onObserverAdded(observer);
  6685. }
  6686. return observer;
  6687. };
  6688. /**
  6689. * Remove an Observer from the Observable object
  6690. * @param observer the instance of the Observer to remove
  6691. * @returns false if it doesn't belong to this Observable
  6692. */
  6693. Observable.prototype.remove = function (observer) {
  6694. if (!observer) {
  6695. return false;
  6696. }
  6697. var index = this._observers.indexOf(observer);
  6698. if (index !== -1) {
  6699. this._observers.splice(index, 1);
  6700. return true;
  6701. }
  6702. return false;
  6703. };
  6704. /**
  6705. * Remove a callback from the Observable object
  6706. * @param callback the callback to remove
  6707. * @param scope optional scope. If used only the callbacks with this scope will be removed
  6708. * @returns false if it doesn't belong to this Observable
  6709. */
  6710. Observable.prototype.removeCallback = function (callback, scope) {
  6711. for (var index = 0; index < this._observers.length; index++) {
  6712. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6713. this._observers.splice(index, 1);
  6714. return true;
  6715. }
  6716. }
  6717. return false;
  6718. };
  6719. Observable.prototype._deferUnregister = function (observer) {
  6720. var _this = this;
  6721. BABYLON.Tools.SetImmediate(function () {
  6722. _this.remove(observer);
  6723. });
  6724. };
  6725. /**
  6726. * Notify all Observers by calling their respective callback with the given data
  6727. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6728. * @param eventData defines the data to send to all observers
  6729. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  6730. * @param target defines the original target of the state
  6731. * @param currentTarget defines the current target of the state
  6732. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  6733. */
  6734. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6735. if (mask === void 0) { mask = -1; }
  6736. if (!this._observers.length) {
  6737. return true;
  6738. }
  6739. var state = this._eventState;
  6740. state.mask = mask;
  6741. state.target = target;
  6742. state.currentTarget = currentTarget;
  6743. state.skipNextObservers = false;
  6744. state.lastReturnValue = eventData;
  6745. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6746. var obs = _a[_i];
  6747. if (obs.mask & mask) {
  6748. if (obs.scope) {
  6749. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  6750. }
  6751. else {
  6752. state.lastReturnValue = obs.callback(eventData, state);
  6753. }
  6754. if (obs.unregisterOnNextCall) {
  6755. this._deferUnregister(obs);
  6756. }
  6757. }
  6758. if (state.skipNextObservers) {
  6759. return false;
  6760. }
  6761. }
  6762. return true;
  6763. };
  6764. /**
  6765. * Calling this will execute each callback, expecting it to be a promise or return a value.
  6766. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  6767. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  6768. * and it is crucial that all callbacks will be executed.
  6769. * The order of the callbacks is kept, callbacks are not executed parallel.
  6770. *
  6771. * @param eventData The data to be sent to each callback
  6772. * @param mask is used to filter observers defaults to -1
  6773. * @param target defines the callback target (see EventState)
  6774. * @param currentTarget defines he current object in the bubbling phase
  6775. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  6776. */
  6777. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  6778. var _this = this;
  6779. if (mask === void 0) { mask = -1; }
  6780. // create an empty promise
  6781. var p = Promise.resolve(eventData);
  6782. // no observers? return this promise.
  6783. if (!this._observers.length) {
  6784. return p;
  6785. }
  6786. var state = this._eventState;
  6787. state.mask = mask;
  6788. state.target = target;
  6789. state.currentTarget = currentTarget;
  6790. state.skipNextObservers = false;
  6791. // execute one callback after another (not using Promise.all, the order is important)
  6792. this._observers.forEach(function (obs) {
  6793. if (state.skipNextObservers) {
  6794. return;
  6795. }
  6796. if (obs.mask & mask) {
  6797. if (obs.scope) {
  6798. p = p.then(function (lastReturnedValue) {
  6799. state.lastReturnValue = lastReturnedValue;
  6800. return obs.callback.apply(obs.scope, [eventData, state]);
  6801. });
  6802. }
  6803. else {
  6804. p = p.then(function (lastReturnedValue) {
  6805. state.lastReturnValue = lastReturnedValue;
  6806. return obs.callback(eventData, state);
  6807. });
  6808. }
  6809. if (obs.unregisterOnNextCall) {
  6810. _this._deferUnregister(obs);
  6811. }
  6812. }
  6813. });
  6814. // return the eventData
  6815. return p.then(function () { return eventData; });
  6816. };
  6817. /**
  6818. * Notify a specific observer
  6819. * @param observer defines the observer to notify
  6820. * @param eventData defines the data to be sent to each callback
  6821. * @param mask is used to filter observers defaults to -1
  6822. */
  6823. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6824. if (mask === void 0) { mask = -1; }
  6825. var state = this._eventState;
  6826. state.mask = mask;
  6827. state.skipNextObservers = false;
  6828. observer.callback(eventData, state);
  6829. };
  6830. /**
  6831. * Gets a boolean indicating if the observable has at least one observer
  6832. * @returns true is the Observable has at least one Observer registered
  6833. */
  6834. Observable.prototype.hasObservers = function () {
  6835. return this._observers.length > 0;
  6836. };
  6837. /**
  6838. * Clear the list of observers
  6839. */
  6840. Observable.prototype.clear = function () {
  6841. this._observers = new Array();
  6842. this._onObserverAdded = null;
  6843. };
  6844. /**
  6845. * Clone the current observable
  6846. * @returns a new observable
  6847. */
  6848. Observable.prototype.clone = function () {
  6849. var result = new Observable();
  6850. result._observers = this._observers.slice(0);
  6851. return result;
  6852. };
  6853. /**
  6854. * Does this observable handles observer registered with a given mask
  6855. * @param mask defines the mask to be tested
  6856. * @return whether or not one observer registered with the given mask is handeled
  6857. **/
  6858. Observable.prototype.hasSpecificMask = function (mask) {
  6859. if (mask === void 0) { mask = -1; }
  6860. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6861. var obs = _a[_i];
  6862. if (obs.mask & mask || obs.mask === mask) {
  6863. return true;
  6864. }
  6865. }
  6866. return false;
  6867. };
  6868. return Observable;
  6869. }());
  6870. BABYLON.Observable = Observable;
  6871. })(BABYLON || (BABYLON = {}));
  6872. //# sourceMappingURL=babylon.observable.js.map
  6873. var BABYLON;
  6874. (function (BABYLON) {
  6875. var SmartArray = /** @class */ (function () {
  6876. function SmartArray(capacity) {
  6877. this.length = 0;
  6878. this.data = new Array(capacity);
  6879. this._id = SmartArray._GlobalId++;
  6880. }
  6881. SmartArray.prototype.push = function (value) {
  6882. this.data[this.length++] = value;
  6883. if (this.length > this.data.length) {
  6884. this.data.length *= 2;
  6885. }
  6886. };
  6887. SmartArray.prototype.forEach = function (func) {
  6888. for (var index = 0; index < this.length; index++) {
  6889. func(this.data[index]);
  6890. }
  6891. };
  6892. SmartArray.prototype.sort = function (compareFn) {
  6893. this.data.sort(compareFn);
  6894. };
  6895. SmartArray.prototype.reset = function () {
  6896. this.length = 0;
  6897. };
  6898. SmartArray.prototype.dispose = function () {
  6899. this.reset();
  6900. if (this.data) {
  6901. this.data.length = 0;
  6902. this.data = [];
  6903. }
  6904. };
  6905. SmartArray.prototype.concat = function (array) {
  6906. if (array.length === 0) {
  6907. return;
  6908. }
  6909. if (this.length + array.length > this.data.length) {
  6910. this.data.length = (this.length + array.length) * 2;
  6911. }
  6912. for (var index = 0; index < array.length; index++) {
  6913. this.data[this.length++] = (array.data || array)[index];
  6914. }
  6915. };
  6916. SmartArray.prototype.indexOf = function (value) {
  6917. var position = this.data.indexOf(value);
  6918. if (position >= this.length) {
  6919. return -1;
  6920. }
  6921. return position;
  6922. };
  6923. SmartArray.prototype.contains = function (value) {
  6924. return this.data.indexOf(value) !== -1;
  6925. };
  6926. // Statics
  6927. SmartArray._GlobalId = 0;
  6928. return SmartArray;
  6929. }());
  6930. BABYLON.SmartArray = SmartArray;
  6931. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6932. __extends(SmartArrayNoDuplicate, _super);
  6933. function SmartArrayNoDuplicate() {
  6934. var _this = _super !== null && _super.apply(this, arguments) || this;
  6935. _this._duplicateId = 0;
  6936. return _this;
  6937. }
  6938. SmartArrayNoDuplicate.prototype.push = function (value) {
  6939. _super.prototype.push.call(this, value);
  6940. if (!value.__smartArrayFlags) {
  6941. value.__smartArrayFlags = {};
  6942. }
  6943. value.__smartArrayFlags[this._id] = this._duplicateId;
  6944. };
  6945. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6946. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6947. return false;
  6948. }
  6949. this.push(value);
  6950. return true;
  6951. };
  6952. SmartArrayNoDuplicate.prototype.reset = function () {
  6953. _super.prototype.reset.call(this);
  6954. this._duplicateId++;
  6955. };
  6956. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6957. if (array.length === 0) {
  6958. return;
  6959. }
  6960. if (this.length + array.length > this.data.length) {
  6961. this.data.length = (this.length + array.length) * 2;
  6962. }
  6963. for (var index = 0; index < array.length; index++) {
  6964. var item = (array.data || array)[index];
  6965. this.pushNoDuplicate(item);
  6966. }
  6967. };
  6968. return SmartArrayNoDuplicate;
  6969. }(SmartArray));
  6970. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6971. })(BABYLON || (BABYLON = {}));
  6972. //# sourceMappingURL=babylon.smartArray.js.map
  6973. var BABYLON;
  6974. (function (BABYLON) {
  6975. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6976. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6977. var LoadFileError = /** @class */ (function (_super) {
  6978. __extends(LoadFileError, _super);
  6979. function LoadFileError(message, request) {
  6980. var _this = _super.call(this, message) || this;
  6981. _this.request = request;
  6982. _this.name = "LoadFileError";
  6983. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6984. return _this;
  6985. }
  6986. // Polyfill for Object.setPrototypeOf if necessary.
  6987. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6988. return LoadFileError;
  6989. }(Error));
  6990. BABYLON.LoadFileError = LoadFileError;
  6991. var RetryStrategy = /** @class */ (function () {
  6992. function RetryStrategy() {
  6993. }
  6994. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6995. if (maxRetries === void 0) { maxRetries = 3; }
  6996. if (baseInterval === void 0) { baseInterval = 500; }
  6997. return function (url, request, retryIndex) {
  6998. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6999. return -1;
  7000. }
  7001. return Math.pow(2, retryIndex) * baseInterval;
  7002. };
  7003. };
  7004. return RetryStrategy;
  7005. }());
  7006. BABYLON.RetryStrategy = RetryStrategy;
  7007. // Screenshots
  7008. var screenshotCanvas;
  7009. var cloneValue = function (source, destinationObject) {
  7010. if (!source)
  7011. return null;
  7012. if (source instanceof BABYLON.Mesh) {
  7013. return null;
  7014. }
  7015. if (source instanceof BABYLON.SubMesh) {
  7016. return source.clone(destinationObject);
  7017. }
  7018. else if (source.clone) {
  7019. return source.clone();
  7020. }
  7021. return null;
  7022. };
  7023. var Tools = /** @class */ (function () {
  7024. function Tools() {
  7025. }
  7026. /**
  7027. * Interpolates between a and b via alpha
  7028. * @param a The lower value (returned when alpha = 0)
  7029. * @param b The upper value (returned when alpha = 1)
  7030. * @param alpha The interpolation-factor
  7031. * @return The mixed value
  7032. */
  7033. Tools.Mix = function (a, b, alpha) {
  7034. return a * (1 - alpha) + b * alpha;
  7035. };
  7036. Tools.Instantiate = function (className) {
  7037. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7038. return Tools.RegisteredExternalClasses[className];
  7039. }
  7040. var arr = className.split(".");
  7041. var fn = (window || this);
  7042. for (var i = 0, len = arr.length; i < len; i++) {
  7043. fn = fn[arr[i]];
  7044. }
  7045. if (typeof fn !== "function") {
  7046. return null;
  7047. }
  7048. return fn;
  7049. };
  7050. /**
  7051. * Provides a slice function that will work even on IE
  7052. * @param data defines the array to slice
  7053. * @returns the new sliced array
  7054. */
  7055. Tools.Slice = function (data) {
  7056. if (data.slice) {
  7057. return data.slice();
  7058. }
  7059. return Array.prototype.slice.call(data);
  7060. };
  7061. Tools.SetImmediate = function (action) {
  7062. if (window.setImmediate) {
  7063. window.setImmediate(action);
  7064. }
  7065. else {
  7066. setTimeout(action, 1);
  7067. }
  7068. };
  7069. Tools.IsExponentOfTwo = function (value) {
  7070. var count = 1;
  7071. do {
  7072. count *= 2;
  7073. } while (count < value);
  7074. return count === value;
  7075. };
  7076. /**
  7077. * Find the next highest power of two.
  7078. * @param x Number to start search from.
  7079. * @return Next highest power of two.
  7080. */
  7081. Tools.CeilingPOT = function (x) {
  7082. x--;
  7083. x |= x >> 1;
  7084. x |= x >> 2;
  7085. x |= x >> 4;
  7086. x |= x >> 8;
  7087. x |= x >> 16;
  7088. x++;
  7089. return x;
  7090. };
  7091. /**
  7092. * Find the next lowest power of two.
  7093. * @param x Number to start search from.
  7094. * @return Next lowest power of two.
  7095. */
  7096. Tools.FloorPOT = function (x) {
  7097. x = x | (x >> 1);
  7098. x = x | (x >> 2);
  7099. x = x | (x >> 4);
  7100. x = x | (x >> 8);
  7101. x = x | (x >> 16);
  7102. return x - (x >> 1);
  7103. };
  7104. /**
  7105. * Find the nearest power of two.
  7106. * @param x Number to start search from.
  7107. * @return Next nearest power of two.
  7108. */
  7109. Tools.NearestPOT = function (x) {
  7110. var c = Tools.CeilingPOT(x);
  7111. var f = Tools.FloorPOT(x);
  7112. return (c - x) > (x - f) ? f : c;
  7113. };
  7114. Tools.GetExponentOfTwo = function (value, max, mode) {
  7115. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7116. var pot;
  7117. switch (mode) {
  7118. case BABYLON.Engine.SCALEMODE_FLOOR:
  7119. pot = Tools.FloorPOT(value);
  7120. break;
  7121. case BABYLON.Engine.SCALEMODE_NEAREST:
  7122. pot = Tools.NearestPOT(value);
  7123. break;
  7124. case BABYLON.Engine.SCALEMODE_CEILING:
  7125. default:
  7126. pot = Tools.CeilingPOT(value);
  7127. break;
  7128. }
  7129. return Math.min(pot, max);
  7130. };
  7131. Tools.GetFilename = function (path) {
  7132. var index = path.lastIndexOf("/");
  7133. if (index < 0)
  7134. return path;
  7135. return path.substring(index + 1);
  7136. };
  7137. /**
  7138. * Extracts the "folder" part of a path (everything before the filename).
  7139. * @param uri The URI to extract the info from
  7140. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7141. * @returns The "folder" part of the path
  7142. */
  7143. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7144. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7145. var index = uri.lastIndexOf("/");
  7146. if (index < 0) {
  7147. if (returnUnchangedIfNoSlash) {
  7148. return uri;
  7149. }
  7150. return "";
  7151. }
  7152. return uri.substring(0, index + 1);
  7153. };
  7154. Tools.GetDOMTextContent = function (element) {
  7155. var result = "";
  7156. var child = element.firstChild;
  7157. while (child) {
  7158. if (child.nodeType === 3) {
  7159. result += child.textContent;
  7160. }
  7161. child = child.nextSibling;
  7162. }
  7163. return result;
  7164. };
  7165. Tools.ToDegrees = function (angle) {
  7166. return angle * 180 / Math.PI;
  7167. };
  7168. Tools.ToRadians = function (angle) {
  7169. return angle * Math.PI / 180;
  7170. };
  7171. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7172. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7173. var output = "";
  7174. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7175. var i = 0;
  7176. var bytes = new Uint8Array(buffer);
  7177. while (i < bytes.length) {
  7178. chr1 = bytes[i++];
  7179. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7180. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7181. enc1 = chr1 >> 2;
  7182. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7183. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7184. enc4 = chr3 & 63;
  7185. if (isNaN(chr2)) {
  7186. enc3 = enc4 = 64;
  7187. }
  7188. else if (isNaN(chr3)) {
  7189. enc4 = 64;
  7190. }
  7191. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7192. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7193. }
  7194. return "data:image/png;base64," + output;
  7195. };
  7196. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7197. if (bias === void 0) { bias = null; }
  7198. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7199. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7200. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7201. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7202. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7203. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7204. }
  7205. if (bias) {
  7206. minimum.x -= minimum.x * bias.x + bias.y;
  7207. minimum.y -= minimum.y * bias.x + bias.y;
  7208. minimum.z -= minimum.z * bias.x + bias.y;
  7209. maximum.x += maximum.x * bias.x + bias.y;
  7210. maximum.y += maximum.y * bias.x + bias.y;
  7211. maximum.z += maximum.z * bias.x + bias.y;
  7212. }
  7213. return {
  7214. minimum: minimum,
  7215. maximum: maximum
  7216. };
  7217. };
  7218. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7219. if (bias === void 0) { bias = null; }
  7220. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7221. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7222. if (!stride) {
  7223. stride = 3;
  7224. }
  7225. for (var index = start; index < start + count; index++) {
  7226. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7227. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7228. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7229. }
  7230. if (bias) {
  7231. minimum.x -= minimum.x * bias.x + bias.y;
  7232. minimum.y -= minimum.y * bias.x + bias.y;
  7233. minimum.z -= minimum.z * bias.x + bias.y;
  7234. maximum.x += maximum.x * bias.x + bias.y;
  7235. maximum.y += maximum.y * bias.x + bias.y;
  7236. maximum.z += maximum.z * bias.x + bias.y;
  7237. }
  7238. return {
  7239. minimum: minimum,
  7240. maximum: maximum
  7241. };
  7242. };
  7243. Tools.Vector2ArrayFeeder = function (array) {
  7244. return function (index) {
  7245. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7246. var length = isFloatArray ? array.length / 2 : array.length;
  7247. if (index >= length) {
  7248. return null;
  7249. }
  7250. if (isFloatArray) {
  7251. var fa = array;
  7252. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7253. }
  7254. var a = array;
  7255. return a[index];
  7256. };
  7257. };
  7258. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7259. if (bias === void 0) { bias = null; }
  7260. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7261. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7262. var i = 0;
  7263. var cur = feeder(i++);
  7264. while (cur) {
  7265. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7266. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7267. cur = feeder(i++);
  7268. }
  7269. if (bias) {
  7270. minimum.x -= minimum.x * bias.x + bias.y;
  7271. minimum.y -= minimum.y * bias.x + bias.y;
  7272. maximum.x += maximum.x * bias.x + bias.y;
  7273. maximum.y += maximum.y * bias.x + bias.y;
  7274. }
  7275. return {
  7276. minimum: minimum,
  7277. maximum: maximum
  7278. };
  7279. };
  7280. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7281. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7282. return null;
  7283. return Array.isArray(obj) ? obj : [obj];
  7284. };
  7285. // Misc.
  7286. Tools.GetPointerPrefix = function () {
  7287. var eventPrefix = "pointer";
  7288. // Check if pointer events are supported
  7289. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7290. eventPrefix = "mouse";
  7291. }
  7292. return eventPrefix;
  7293. };
  7294. /**
  7295. * @param func - the function to be called
  7296. * @param requester - the object that will request the next frame. Falls back to window.
  7297. */
  7298. Tools.QueueNewFrame = function (func, requester) {
  7299. if (!Tools.IsWindowObjectExist()) {
  7300. return setTimeout(func, 16);
  7301. }
  7302. if (!requester) {
  7303. requester = window;
  7304. }
  7305. if (requester.requestAnimationFrame) {
  7306. return requester.requestAnimationFrame(func);
  7307. }
  7308. else if (requester.msRequestAnimationFrame) {
  7309. return requester.msRequestAnimationFrame(func);
  7310. }
  7311. else if (requester.webkitRequestAnimationFrame) {
  7312. return requester.webkitRequestAnimationFrame(func);
  7313. }
  7314. else if (requester.mozRequestAnimationFrame) {
  7315. return requester.mozRequestAnimationFrame(func);
  7316. }
  7317. else if (requester.oRequestAnimationFrame) {
  7318. return requester.oRequestAnimationFrame(func);
  7319. }
  7320. else {
  7321. return window.setTimeout(func, 16);
  7322. }
  7323. };
  7324. Tools.RequestFullscreen = function (element) {
  7325. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7326. if (!requestFunction)
  7327. return;
  7328. requestFunction.call(element);
  7329. };
  7330. Tools.ExitFullscreen = function () {
  7331. if (document.exitFullscreen) {
  7332. document.exitFullscreen();
  7333. }
  7334. else if (document.mozCancelFullScreen) {
  7335. document.mozCancelFullScreen();
  7336. }
  7337. else if (document.webkitCancelFullScreen) {
  7338. document.webkitCancelFullScreen();
  7339. }
  7340. else if (document.msCancelFullScreen) {
  7341. document.msCancelFullScreen();
  7342. }
  7343. };
  7344. Tools.SetCorsBehavior = function (url, element) {
  7345. if (url && url.indexOf("data:") === 0) {
  7346. return;
  7347. }
  7348. if (Tools.CorsBehavior) {
  7349. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7350. element.crossOrigin = Tools.CorsBehavior;
  7351. }
  7352. else {
  7353. var result = Tools.CorsBehavior(url);
  7354. if (result) {
  7355. element.crossOrigin = result;
  7356. }
  7357. }
  7358. }
  7359. };
  7360. // External files
  7361. Tools.CleanUrl = function (url) {
  7362. url = url.replace(/#/mg, "%23");
  7363. return url;
  7364. };
  7365. Tools.LoadImage = function (url, onLoad, onError, database) {
  7366. if (url instanceof ArrayBuffer) {
  7367. url = Tools.EncodeArrayBufferTobase64(url);
  7368. }
  7369. url = Tools.CleanUrl(url);
  7370. url = Tools.PreprocessUrl(url);
  7371. var img = new Image();
  7372. Tools.SetCorsBehavior(url, img);
  7373. img.onload = function () {
  7374. onLoad(img);
  7375. };
  7376. img.onerror = function (err) {
  7377. Tools.Error("Error while trying to load image: " + url);
  7378. if (onError) {
  7379. onError("Error while trying to load image: " + url, err);
  7380. }
  7381. };
  7382. var noIndexedDB = function () {
  7383. img.src = url;
  7384. };
  7385. var loadFromIndexedDB = function () {
  7386. if (database) {
  7387. database.loadImageFromDB(url, img);
  7388. }
  7389. };
  7390. //ANY database to do!
  7391. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7392. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7393. }
  7394. else {
  7395. if (url.indexOf("file:") !== -1) {
  7396. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7397. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7398. try {
  7399. var blobURL;
  7400. try {
  7401. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7402. }
  7403. catch (ex) {
  7404. // Chrome doesn't support oneTimeOnly parameter
  7405. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7406. }
  7407. img.src = blobURL;
  7408. }
  7409. catch (e) {
  7410. img.src = "";
  7411. }
  7412. return img;
  7413. }
  7414. }
  7415. noIndexedDB();
  7416. }
  7417. return img;
  7418. };
  7419. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7420. url = Tools.CleanUrl(url);
  7421. url = Tools.PreprocessUrl(url);
  7422. // If file and file input are set
  7423. if (url.indexOf("file:") !== -1) {
  7424. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7425. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7426. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7427. }
  7428. }
  7429. var loadUrl = Tools.BaseUrl + url;
  7430. var aborted = false;
  7431. var fileRequest = {
  7432. onCompleteObservable: new BABYLON.Observable(),
  7433. abort: function () { return aborted = true; },
  7434. };
  7435. var requestFile = function () {
  7436. var request = new XMLHttpRequest();
  7437. var retryHandle = null;
  7438. fileRequest.abort = function () {
  7439. aborted = true;
  7440. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7441. request.abort();
  7442. }
  7443. if (retryHandle !== null) {
  7444. clearTimeout(retryHandle);
  7445. retryHandle = null;
  7446. }
  7447. };
  7448. var retryLoop = function (retryIndex) {
  7449. request.open('GET', loadUrl, true);
  7450. if (useArrayBuffer) {
  7451. request.responseType = "arraybuffer";
  7452. }
  7453. if (onProgress) {
  7454. request.addEventListener("progress", onProgress);
  7455. }
  7456. var onLoadEnd = function () {
  7457. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7458. };
  7459. request.addEventListener("loadend", onLoadEnd);
  7460. var onReadyStateChange = function () {
  7461. if (aborted) {
  7462. return;
  7463. }
  7464. // In case of undefined state in some browsers.
  7465. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7466. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7467. request.removeEventListener("readystatechange", onReadyStateChange);
  7468. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7469. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7470. return;
  7471. }
  7472. var retryStrategy = Tools.DefaultRetryStrategy;
  7473. if (retryStrategy) {
  7474. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7475. if (waitTime !== -1) {
  7476. // Prevent the request from completing for retry.
  7477. request.removeEventListener("loadend", onLoadEnd);
  7478. request = new XMLHttpRequest();
  7479. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7480. return;
  7481. }
  7482. }
  7483. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7484. if (onError) {
  7485. onError(request, e);
  7486. }
  7487. else {
  7488. throw e;
  7489. }
  7490. }
  7491. };
  7492. request.addEventListener("readystatechange", onReadyStateChange);
  7493. request.send();
  7494. };
  7495. retryLoop(0);
  7496. };
  7497. // Caching all files
  7498. if (database && database.enableSceneOffline) {
  7499. var noIndexedDB_1 = function () {
  7500. if (!aborted) {
  7501. requestFile();
  7502. }
  7503. };
  7504. var loadFromIndexedDB = function () {
  7505. // TODO: database needs to support aborting and should return a IFileRequest
  7506. if (aborted) {
  7507. return;
  7508. }
  7509. if (database) {
  7510. database.loadFileFromDB(url, function (data) {
  7511. if (!aborted) {
  7512. onSuccess(data);
  7513. }
  7514. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7515. }, onProgress ? function (event) {
  7516. if (!aborted) {
  7517. onProgress(event);
  7518. }
  7519. } : undefined, noIndexedDB_1, useArrayBuffer);
  7520. }
  7521. };
  7522. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7523. }
  7524. else {
  7525. requestFile();
  7526. }
  7527. return fileRequest;
  7528. };
  7529. /**
  7530. * Load a script (identified by an url). When the url returns, the
  7531. * content of this file is added into a new script element, attached to the DOM (body element)
  7532. */
  7533. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7534. var head = document.getElementsByTagName('head')[0];
  7535. var script = document.createElement('script');
  7536. script.type = 'text/javascript';
  7537. script.src = scriptUrl;
  7538. script.onload = function () {
  7539. if (onSuccess) {
  7540. onSuccess();
  7541. }
  7542. };
  7543. script.onerror = function (e) {
  7544. if (onError) {
  7545. onError("Unable to load script", e);
  7546. }
  7547. };
  7548. head.appendChild(script);
  7549. };
  7550. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7551. var reader = new FileReader();
  7552. var request = {
  7553. onCompleteObservable: new BABYLON.Observable(),
  7554. abort: function () { return reader.abort(); },
  7555. };
  7556. reader.onloadend = function (e) {
  7557. request.onCompleteObservable.notifyObservers(request);
  7558. };
  7559. reader.onload = function (e) {
  7560. //target doesn't have result from ts 1.3
  7561. callback(e.target['result']);
  7562. };
  7563. reader.onprogress = progressCallback;
  7564. reader.readAsDataURL(fileToLoad);
  7565. return request;
  7566. };
  7567. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7568. var reader = new FileReader();
  7569. var request = {
  7570. onCompleteObservable: new BABYLON.Observable(),
  7571. abort: function () { return reader.abort(); },
  7572. };
  7573. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7574. reader.onerror = function (e) {
  7575. Tools.Log("Error while reading file: " + fileToLoad.name);
  7576. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7577. };
  7578. reader.onload = function (e) {
  7579. //target doesn't have result from ts 1.3
  7580. callback(e.target['result']);
  7581. };
  7582. if (progressCallBack) {
  7583. reader.onprogress = progressCallBack;
  7584. }
  7585. if (!useArrayBuffer) {
  7586. // Asynchronous read
  7587. reader.readAsText(fileToLoad);
  7588. }
  7589. else {
  7590. reader.readAsArrayBuffer(fileToLoad);
  7591. }
  7592. return request;
  7593. };
  7594. //returns a downloadable url to a file content.
  7595. Tools.FileAsURL = function (content) {
  7596. var fileBlob = new Blob([content]);
  7597. var url = window.URL || window.webkitURL;
  7598. var link = url.createObjectURL(fileBlob);
  7599. return link;
  7600. };
  7601. // Misc.
  7602. Tools.Format = function (value, decimals) {
  7603. if (decimals === void 0) { decimals = 2; }
  7604. return value.toFixed(decimals);
  7605. };
  7606. Tools.CheckExtends = function (v, min, max) {
  7607. if (v.x < min.x)
  7608. min.x = v.x;
  7609. if (v.y < min.y)
  7610. min.y = v.y;
  7611. if (v.z < min.z)
  7612. min.z = v.z;
  7613. if (v.x > max.x)
  7614. max.x = v.x;
  7615. if (v.y > max.y)
  7616. max.y = v.y;
  7617. if (v.z > max.z)
  7618. max.z = v.z;
  7619. };
  7620. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7621. for (var prop in source) {
  7622. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7623. continue;
  7624. }
  7625. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7626. continue;
  7627. }
  7628. var sourceValue = source[prop];
  7629. var typeOfSourceValue = typeof sourceValue;
  7630. if (typeOfSourceValue === "function") {
  7631. continue;
  7632. }
  7633. if (typeOfSourceValue === "object") {
  7634. if (sourceValue instanceof Array) {
  7635. destination[prop] = [];
  7636. if (sourceValue.length > 0) {
  7637. if (typeof sourceValue[0] == "object") {
  7638. for (var index = 0; index < sourceValue.length; index++) {
  7639. var clonedValue = cloneValue(sourceValue[index], destination);
  7640. if (destination[prop].indexOf(clonedValue) === -1) {
  7641. destination[prop].push(clonedValue);
  7642. }
  7643. }
  7644. }
  7645. else {
  7646. destination[prop] = sourceValue.slice(0);
  7647. }
  7648. }
  7649. }
  7650. else {
  7651. destination[prop] = cloneValue(sourceValue, destination);
  7652. }
  7653. }
  7654. else {
  7655. destination[prop] = sourceValue;
  7656. }
  7657. }
  7658. };
  7659. Tools.IsEmpty = function (obj) {
  7660. for (var i in obj) {
  7661. if (obj.hasOwnProperty(i)) {
  7662. return false;
  7663. }
  7664. }
  7665. return true;
  7666. };
  7667. Tools.RegisterTopRootEvents = function (events) {
  7668. for (var index = 0; index < events.length; index++) {
  7669. var event = events[index];
  7670. window.addEventListener(event.name, event.handler, false);
  7671. try {
  7672. if (window.parent) {
  7673. window.parent.addEventListener(event.name, event.handler, false);
  7674. }
  7675. }
  7676. catch (e) {
  7677. // Silently fails...
  7678. }
  7679. }
  7680. };
  7681. Tools.UnregisterTopRootEvents = function (events) {
  7682. for (var index = 0; index < events.length; index++) {
  7683. var event = events[index];
  7684. window.removeEventListener(event.name, event.handler);
  7685. try {
  7686. if (window.parent) {
  7687. window.parent.removeEventListener(event.name, event.handler);
  7688. }
  7689. }
  7690. catch (e) {
  7691. // Silently fails...
  7692. }
  7693. }
  7694. };
  7695. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7696. if (mimeType === void 0) { mimeType = "image/png"; }
  7697. // Read the contents of the framebuffer
  7698. var numberOfChannelsByLine = width * 4;
  7699. var halfHeight = height / 2;
  7700. //Reading datas from WebGL
  7701. var data = engine.readPixels(0, 0, width, height);
  7702. //To flip image on Y axis.
  7703. for (var i = 0; i < halfHeight; i++) {
  7704. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7705. var currentCell = j + i * numberOfChannelsByLine;
  7706. var targetLine = height - i - 1;
  7707. var targetCell = j + targetLine * numberOfChannelsByLine;
  7708. var temp = data[currentCell];
  7709. data[currentCell] = data[targetCell];
  7710. data[targetCell] = temp;
  7711. }
  7712. }
  7713. // Create a 2D canvas to store the result
  7714. if (!screenshotCanvas) {
  7715. screenshotCanvas = document.createElement('canvas');
  7716. }
  7717. screenshotCanvas.width = width;
  7718. screenshotCanvas.height = height;
  7719. var context = screenshotCanvas.getContext('2d');
  7720. if (context) {
  7721. // Copy the pixels to a 2D canvas
  7722. var imageData = context.createImageData(width, height);
  7723. var castData = (imageData.data);
  7724. castData.set(data);
  7725. context.putImageData(imageData, 0, 0);
  7726. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7727. }
  7728. };
  7729. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7730. if (mimeType === void 0) { mimeType = "image/png"; }
  7731. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7732. if (successCallback) {
  7733. successCallback(base64Image);
  7734. }
  7735. else {
  7736. // We need HTMLCanvasElement.toBlob for HD screenshots
  7737. if (!screenshotCanvas.toBlob) {
  7738. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7739. screenshotCanvas.toBlob = function (callback, type, quality) {
  7740. var _this = this;
  7741. setTimeout(function () {
  7742. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7743. for (var i = 0; i < len; i++) {
  7744. arr[i] = binStr.charCodeAt(i);
  7745. }
  7746. callback(new Blob([arr], { type: type || 'image/png' }));
  7747. });
  7748. };
  7749. }
  7750. screenshotCanvas.toBlob(function (blob) {
  7751. var url = URL.createObjectURL(blob);
  7752. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7753. if (("download" in document.createElement("a"))) {
  7754. var a = window.document.createElement("a");
  7755. a.href = url;
  7756. if (fileName) {
  7757. a.setAttribute("download", fileName);
  7758. }
  7759. else {
  7760. var date = new Date();
  7761. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7762. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7763. }
  7764. window.document.body.appendChild(a);
  7765. a.addEventListener("click", function () {
  7766. if (a.parentElement) {
  7767. a.parentElement.removeChild(a);
  7768. }
  7769. });
  7770. a.click();
  7771. }
  7772. else {
  7773. var newWindow = window.open("");
  7774. if (!newWindow)
  7775. return;
  7776. var img = newWindow.document.createElement("img");
  7777. img.onload = function () {
  7778. // no longer need to read the blob so it's revoked
  7779. URL.revokeObjectURL(url);
  7780. };
  7781. img.src = url;
  7782. newWindow.document.body.appendChild(img);
  7783. }
  7784. });
  7785. }
  7786. };
  7787. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7788. if (mimeType === void 0) { mimeType = "image/png"; }
  7789. var width;
  7790. var height;
  7791. // If a precision value is specified
  7792. if (size.precision) {
  7793. width = Math.round(engine.getRenderWidth() * size.precision);
  7794. height = Math.round(width / engine.getAspectRatio(camera));
  7795. }
  7796. else if (size.width && size.height) {
  7797. width = size.width;
  7798. height = size.height;
  7799. }
  7800. else if (size.width && !size.height) {
  7801. width = size.width;
  7802. height = Math.round(width / engine.getAspectRatio(camera));
  7803. }
  7804. else if (size.height && !size.width) {
  7805. height = size.height;
  7806. width = Math.round(height * engine.getAspectRatio(camera));
  7807. }
  7808. else if (!isNaN(size)) {
  7809. height = size;
  7810. width = size;
  7811. }
  7812. else {
  7813. Tools.Error("Invalid 'size' parameter !");
  7814. return;
  7815. }
  7816. if (!screenshotCanvas) {
  7817. screenshotCanvas = document.createElement('canvas');
  7818. }
  7819. screenshotCanvas.width = width;
  7820. screenshotCanvas.height = height;
  7821. var renderContext = screenshotCanvas.getContext("2d");
  7822. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7823. var newWidth = width;
  7824. var newHeight = newWidth / ratio;
  7825. if (newHeight > height) {
  7826. newHeight = height;
  7827. newWidth = newHeight * ratio;
  7828. }
  7829. var offsetX = Math.max(0, width - newWidth) / 2;
  7830. var offsetY = Math.max(0, height - newHeight) / 2;
  7831. var renderingCanvas = engine.getRenderingCanvas();
  7832. if (renderContext && renderingCanvas) {
  7833. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7834. }
  7835. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7836. };
  7837. /**
  7838. * Generates an image screenshot from the specified camera.
  7839. *
  7840. * @param engine The engine to use for rendering
  7841. * @param camera The camera to use for rendering
  7842. * @param size This parameter can be set to a single number or to an object with the
  7843. * following (optional) properties: precision, width, height. If a single number is passed,
  7844. * it will be used for both width and height. If an object is passed, the screenshot size
  7845. * will be derived from the parameters. The precision property is a multiplier allowing
  7846. * rendering at a higher or lower resolution.
  7847. * @param successCallback The callback receives a single parameter which contains the
  7848. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7849. * src parameter of an <img> to display it.
  7850. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7851. * Check your browser for supported MIME types.
  7852. * @param samples Texture samples (default: 1)
  7853. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7854. * @param fileName A name for for the downloaded file.
  7855. * @constructor
  7856. */
  7857. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7858. if (mimeType === void 0) { mimeType = "image/png"; }
  7859. if (samples === void 0) { samples = 1; }
  7860. if (antialiasing === void 0) { antialiasing = false; }
  7861. var width;
  7862. var height;
  7863. //If a precision value is specified
  7864. if (size.precision) {
  7865. width = Math.round(engine.getRenderWidth() * size.precision);
  7866. height = Math.round(width / engine.getAspectRatio(camera));
  7867. size = { width: width, height: height };
  7868. }
  7869. else if (size.width && size.height) {
  7870. width = size.width;
  7871. height = size.height;
  7872. }
  7873. else if (size.width && !size.height) {
  7874. width = size.width;
  7875. height = Math.round(width / engine.getAspectRatio(camera));
  7876. size = { width: width, height: height };
  7877. }
  7878. else if (size.height && !size.width) {
  7879. height = size.height;
  7880. width = Math.round(height * engine.getAspectRatio(camera));
  7881. size = { width: width, height: height };
  7882. }
  7883. else if (!isNaN(size)) {
  7884. height = size;
  7885. width = size;
  7886. }
  7887. else {
  7888. Tools.Error("Invalid 'size' parameter !");
  7889. return;
  7890. }
  7891. var scene = camera.getScene();
  7892. var previousCamera = null;
  7893. if (scene.activeCamera !== camera) {
  7894. previousCamera = scene.activeCamera;
  7895. scene.activeCamera = camera;
  7896. }
  7897. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7898. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7899. texture.renderList = null;
  7900. texture.samples = samples;
  7901. if (antialiasing) {
  7902. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7903. }
  7904. texture.onAfterRenderObservable.add(function () {
  7905. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7906. });
  7907. scene.incrementRenderId();
  7908. scene.resetCachedMaterial();
  7909. texture.render(true);
  7910. texture.dispose();
  7911. if (previousCamera) {
  7912. scene.activeCamera = previousCamera;
  7913. }
  7914. camera.getProjectionMatrix(true); // Force cache refresh;
  7915. };
  7916. // XHR response validator for local file scenario
  7917. Tools.ValidateXHRData = function (xhr, dataType) {
  7918. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7919. if (dataType === void 0) { dataType = 7; }
  7920. try {
  7921. if (dataType & 1) {
  7922. if (xhr.responseText && xhr.responseText.length > 0) {
  7923. return true;
  7924. }
  7925. else if (dataType === 1) {
  7926. return false;
  7927. }
  7928. }
  7929. if (dataType & 2) {
  7930. // Check header width and height since there is no "TGA" magic number
  7931. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7932. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7933. return true;
  7934. }
  7935. else if (dataType === 2) {
  7936. return false;
  7937. }
  7938. }
  7939. if (dataType & 4) {
  7940. // Check for the "DDS" magic number
  7941. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7942. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7943. return true;
  7944. }
  7945. else {
  7946. return false;
  7947. }
  7948. }
  7949. }
  7950. catch (e) {
  7951. // Global protection
  7952. }
  7953. return false;
  7954. };
  7955. /**
  7956. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7957. * Be aware Math.random() could cause collisions, but:
  7958. * "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"
  7959. */
  7960. Tools.RandomId = function () {
  7961. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7962. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7963. return v.toString(16);
  7964. });
  7965. };
  7966. /**
  7967. * Test if the given uri is a base64 string.
  7968. * @param uri The uri to test
  7969. * @return True if the uri is a base64 string or false otherwise.
  7970. */
  7971. Tools.IsBase64 = function (uri) {
  7972. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  7973. };
  7974. /**
  7975. * Decode the given base64 uri.
  7976. * @param uri The uri to decode
  7977. * @return The decoded base64 data.
  7978. */
  7979. Tools.DecodeBase64 = function (uri) {
  7980. var decodedString = atob(uri.split(",")[1]);
  7981. var bufferLength = decodedString.length;
  7982. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  7983. for (var i = 0; i < bufferLength; i++) {
  7984. bufferView[i] = decodedString.charCodeAt(i);
  7985. }
  7986. return bufferView.buffer;
  7987. };
  7988. Object.defineProperty(Tools, "NoneLogLevel", {
  7989. get: function () {
  7990. return Tools._NoneLogLevel;
  7991. },
  7992. enumerable: true,
  7993. configurable: true
  7994. });
  7995. Object.defineProperty(Tools, "MessageLogLevel", {
  7996. get: function () {
  7997. return Tools._MessageLogLevel;
  7998. },
  7999. enumerable: true,
  8000. configurable: true
  8001. });
  8002. Object.defineProperty(Tools, "WarningLogLevel", {
  8003. get: function () {
  8004. return Tools._WarningLogLevel;
  8005. },
  8006. enumerable: true,
  8007. configurable: true
  8008. });
  8009. Object.defineProperty(Tools, "ErrorLogLevel", {
  8010. get: function () {
  8011. return Tools._ErrorLogLevel;
  8012. },
  8013. enumerable: true,
  8014. configurable: true
  8015. });
  8016. Object.defineProperty(Tools, "AllLogLevel", {
  8017. get: function () {
  8018. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8019. },
  8020. enumerable: true,
  8021. configurable: true
  8022. });
  8023. Tools._AddLogEntry = function (entry) {
  8024. Tools._LogCache = entry + Tools._LogCache;
  8025. if (Tools.OnNewCacheEntry) {
  8026. Tools.OnNewCacheEntry(entry);
  8027. }
  8028. };
  8029. Tools._FormatMessage = function (message) {
  8030. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8031. var date = new Date();
  8032. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8033. };
  8034. Tools._LogDisabled = function (message) {
  8035. // nothing to do
  8036. };
  8037. Tools._LogEnabled = function (message) {
  8038. var formattedMessage = Tools._FormatMessage(message);
  8039. console.log("BJS - " + formattedMessage);
  8040. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8041. Tools._AddLogEntry(entry);
  8042. };
  8043. Tools._WarnDisabled = function (message) {
  8044. // nothing to do
  8045. };
  8046. Tools._WarnEnabled = function (message) {
  8047. var formattedMessage = Tools._FormatMessage(message);
  8048. console.warn("BJS - " + formattedMessage);
  8049. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8050. Tools._AddLogEntry(entry);
  8051. };
  8052. Tools._ErrorDisabled = function (message) {
  8053. // nothing to do
  8054. };
  8055. Tools._ErrorEnabled = function (message) {
  8056. Tools.errorsCount++;
  8057. var formattedMessage = Tools._FormatMessage(message);
  8058. console.error("BJS - " + formattedMessage);
  8059. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8060. Tools._AddLogEntry(entry);
  8061. };
  8062. Object.defineProperty(Tools, "LogCache", {
  8063. get: function () {
  8064. return Tools._LogCache;
  8065. },
  8066. enumerable: true,
  8067. configurable: true
  8068. });
  8069. Tools.ClearLogCache = function () {
  8070. Tools._LogCache = "";
  8071. Tools.errorsCount = 0;
  8072. };
  8073. Object.defineProperty(Tools, "LogLevels", {
  8074. set: function (level) {
  8075. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8076. Tools.Log = Tools._LogEnabled;
  8077. }
  8078. else {
  8079. Tools.Log = Tools._LogDisabled;
  8080. }
  8081. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8082. Tools.Warn = Tools._WarnEnabled;
  8083. }
  8084. else {
  8085. Tools.Warn = Tools._WarnDisabled;
  8086. }
  8087. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8088. Tools.Error = Tools._ErrorEnabled;
  8089. }
  8090. else {
  8091. Tools.Error = Tools._ErrorDisabled;
  8092. }
  8093. },
  8094. enumerable: true,
  8095. configurable: true
  8096. });
  8097. Tools.IsWindowObjectExist = function () {
  8098. return (typeof window) !== "undefined";
  8099. };
  8100. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8101. get: function () {
  8102. return Tools._PerformanceNoneLogLevel;
  8103. },
  8104. enumerable: true,
  8105. configurable: true
  8106. });
  8107. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8108. get: function () {
  8109. return Tools._PerformanceUserMarkLogLevel;
  8110. },
  8111. enumerable: true,
  8112. configurable: true
  8113. });
  8114. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8115. get: function () {
  8116. return Tools._PerformanceConsoleLogLevel;
  8117. },
  8118. enumerable: true,
  8119. configurable: true
  8120. });
  8121. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8122. set: function (level) {
  8123. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8124. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8125. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8126. return;
  8127. }
  8128. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8129. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8130. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8131. return;
  8132. }
  8133. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8134. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8135. },
  8136. enumerable: true,
  8137. configurable: true
  8138. });
  8139. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8140. };
  8141. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8142. };
  8143. Tools._StartUserMark = function (counterName, condition) {
  8144. if (condition === void 0) { condition = true; }
  8145. if (!Tools._performance) {
  8146. if (!Tools.IsWindowObjectExist()) {
  8147. return;
  8148. }
  8149. Tools._performance = window.performance;
  8150. }
  8151. if (!condition || !Tools._performance.mark) {
  8152. return;
  8153. }
  8154. Tools._performance.mark(counterName + "-Begin");
  8155. };
  8156. Tools._EndUserMark = function (counterName, condition) {
  8157. if (condition === void 0) { condition = true; }
  8158. if (!condition || !Tools._performance.mark) {
  8159. return;
  8160. }
  8161. Tools._performance.mark(counterName + "-End");
  8162. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8163. };
  8164. Tools._StartPerformanceConsole = function (counterName, condition) {
  8165. if (condition === void 0) { condition = true; }
  8166. if (!condition) {
  8167. return;
  8168. }
  8169. Tools._StartUserMark(counterName, condition);
  8170. if (console.time) {
  8171. console.time(counterName);
  8172. }
  8173. };
  8174. Tools._EndPerformanceConsole = function (counterName, condition) {
  8175. if (condition === void 0) { condition = true; }
  8176. if (!condition) {
  8177. return;
  8178. }
  8179. Tools._EndUserMark(counterName, condition);
  8180. if (console.time) {
  8181. console.timeEnd(counterName);
  8182. }
  8183. };
  8184. Object.defineProperty(Tools, "Now", {
  8185. get: function () {
  8186. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8187. return window.performance.now();
  8188. }
  8189. return new Date().getTime();
  8190. },
  8191. enumerable: true,
  8192. configurable: true
  8193. });
  8194. /**
  8195. * This method will return the name of the class used to create the instance of the given object.
  8196. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8197. * @param object the object to get the class name from
  8198. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8199. */
  8200. Tools.GetClassName = function (object, isType) {
  8201. if (isType === void 0) { isType = false; }
  8202. var name = null;
  8203. if (!isType && object.getClassName) {
  8204. name = object.getClassName();
  8205. }
  8206. else {
  8207. if (object instanceof Object) {
  8208. var classObj = isType ? object : Object.getPrototypeOf(object);
  8209. name = classObj.constructor["__bjsclassName__"];
  8210. }
  8211. if (!name) {
  8212. name = typeof object;
  8213. }
  8214. }
  8215. return name;
  8216. };
  8217. Tools.First = function (array, predicate) {
  8218. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8219. var el = array_1[_i];
  8220. if (predicate(el)) {
  8221. return el;
  8222. }
  8223. }
  8224. return null;
  8225. };
  8226. /**
  8227. * This method will return the name of the full name of the class, including its owning module (if any).
  8228. * 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).
  8229. * @param object the object to get the class name from
  8230. * @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.
  8231. */
  8232. Tools.getFullClassName = function (object, isType) {
  8233. if (isType === void 0) { isType = false; }
  8234. var className = null;
  8235. var moduleName = null;
  8236. if (!isType && object.getClassName) {
  8237. className = object.getClassName();
  8238. }
  8239. else {
  8240. if (object instanceof Object) {
  8241. var classObj = isType ? object : Object.getPrototypeOf(object);
  8242. className = classObj.constructor["__bjsclassName__"];
  8243. moduleName = classObj.constructor["__bjsmoduleName__"];
  8244. }
  8245. if (!className) {
  8246. className = typeof object;
  8247. }
  8248. }
  8249. if (!className) {
  8250. return null;
  8251. }
  8252. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8253. };
  8254. /**
  8255. * 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.
  8256. * @param array
  8257. */
  8258. Tools.arrayOrStringFeeder = function (array) {
  8259. return function (index) {
  8260. if (index >= array.length) {
  8261. return null;
  8262. }
  8263. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8264. if (val && val.getHashCode) {
  8265. val = val.getHashCode();
  8266. }
  8267. if (typeof val === "string") {
  8268. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8269. }
  8270. return val;
  8271. };
  8272. };
  8273. /**
  8274. * Compute the hashCode of a stream of number
  8275. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8276. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8277. * @return the hash code computed
  8278. */
  8279. Tools.hashCodeFromStream = function (feeder) {
  8280. // Based from here: http://stackoverflow.com/a/7616484/802124
  8281. var hash = 0;
  8282. var index = 0;
  8283. var chr = feeder(index++);
  8284. while (chr != null) {
  8285. hash = ((hash << 5) - hash) + chr;
  8286. hash |= 0; // Convert to 32bit integer
  8287. chr = feeder(index++);
  8288. }
  8289. return hash;
  8290. };
  8291. Tools.BaseUrl = "";
  8292. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8293. /**
  8294. * Default behaviour for cors in the application.
  8295. * It can be a string if the expected behavior is identical in the entire app.
  8296. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8297. */
  8298. Tools.CorsBehavior = "anonymous";
  8299. Tools.UseFallbackTexture = true;
  8300. /**
  8301. * Use this object to register external classes like custom textures or material
  8302. * to allow the laoders to instantiate them
  8303. */
  8304. Tools.RegisteredExternalClasses = {};
  8305. // Used in case of a texture loading problem
  8306. 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";
  8307. Tools.PreprocessUrl = function (url) {
  8308. return url;
  8309. };
  8310. // Logs
  8311. Tools._NoneLogLevel = 0;
  8312. Tools._MessageLogLevel = 1;
  8313. Tools._WarningLogLevel = 2;
  8314. Tools._ErrorLogLevel = 4;
  8315. Tools._LogCache = "";
  8316. Tools.errorsCount = 0;
  8317. Tools.Log = Tools._LogEnabled;
  8318. Tools.Warn = Tools._WarnEnabled;
  8319. Tools.Error = Tools._ErrorEnabled;
  8320. // Performances
  8321. Tools._PerformanceNoneLogLevel = 0;
  8322. Tools._PerformanceUserMarkLogLevel = 1;
  8323. Tools._PerformanceConsoleLogLevel = 2;
  8324. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8325. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8326. return Tools;
  8327. }());
  8328. BABYLON.Tools = Tools;
  8329. /**
  8330. * This class is used to track a performance counter which is number based.
  8331. * The user has access to many properties which give statistics of different nature
  8332. *
  8333. * The implementer can track two kinds of Performance Counter: time and count
  8334. * 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.
  8335. * 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.
  8336. */
  8337. var PerfCounter = /** @class */ (function () {
  8338. function PerfCounter() {
  8339. this._startMonitoringTime = 0;
  8340. this._min = 0;
  8341. this._max = 0;
  8342. this._average = 0;
  8343. this._lastSecAverage = 0;
  8344. this._current = 0;
  8345. this._totalValueCount = 0;
  8346. this._totalAccumulated = 0;
  8347. this._lastSecAccumulated = 0;
  8348. this._lastSecTime = 0;
  8349. this._lastSecValueCount = 0;
  8350. }
  8351. Object.defineProperty(PerfCounter.prototype, "min", {
  8352. /**
  8353. * Returns the smallest value ever
  8354. */
  8355. get: function () {
  8356. return this._min;
  8357. },
  8358. enumerable: true,
  8359. configurable: true
  8360. });
  8361. Object.defineProperty(PerfCounter.prototype, "max", {
  8362. /**
  8363. * Returns the biggest value ever
  8364. */
  8365. get: function () {
  8366. return this._max;
  8367. },
  8368. enumerable: true,
  8369. configurable: true
  8370. });
  8371. Object.defineProperty(PerfCounter.prototype, "average", {
  8372. /**
  8373. * Returns the average value since the performance counter is running
  8374. */
  8375. get: function () {
  8376. return this._average;
  8377. },
  8378. enumerable: true,
  8379. configurable: true
  8380. });
  8381. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8382. /**
  8383. * Returns the average value of the last second the counter was monitored
  8384. */
  8385. get: function () {
  8386. return this._lastSecAverage;
  8387. },
  8388. enumerable: true,
  8389. configurable: true
  8390. });
  8391. Object.defineProperty(PerfCounter.prototype, "current", {
  8392. /**
  8393. * Returns the current value
  8394. */
  8395. get: function () {
  8396. return this._current;
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. Object.defineProperty(PerfCounter.prototype, "total", {
  8402. get: function () {
  8403. return this._totalAccumulated;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Object.defineProperty(PerfCounter.prototype, "count", {
  8409. get: function () {
  8410. return this._totalValueCount;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. /**
  8416. * Call this method to start monitoring a new frame.
  8417. * 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.
  8418. */
  8419. PerfCounter.prototype.fetchNewFrame = function () {
  8420. this._totalValueCount++;
  8421. this._current = 0;
  8422. this._lastSecValueCount++;
  8423. };
  8424. /**
  8425. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8426. * @param newCount the count value to add to the monitored count
  8427. * @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.
  8428. */
  8429. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8430. if (!PerfCounter.Enabled) {
  8431. return;
  8432. }
  8433. this._current += newCount;
  8434. if (fetchResult) {
  8435. this._fetchResult();
  8436. }
  8437. };
  8438. /**
  8439. * Start monitoring this performance counter
  8440. */
  8441. PerfCounter.prototype.beginMonitoring = function () {
  8442. if (!PerfCounter.Enabled) {
  8443. return;
  8444. }
  8445. this._startMonitoringTime = Tools.Now;
  8446. };
  8447. /**
  8448. * Compute the time lapsed since the previous beginMonitoring() call.
  8449. * @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
  8450. */
  8451. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8452. if (newFrame === void 0) { newFrame = true; }
  8453. if (!PerfCounter.Enabled) {
  8454. return;
  8455. }
  8456. if (newFrame) {
  8457. this.fetchNewFrame();
  8458. }
  8459. var currentTime = Tools.Now;
  8460. this._current = currentTime - this._startMonitoringTime;
  8461. if (newFrame) {
  8462. this._fetchResult();
  8463. }
  8464. };
  8465. PerfCounter.prototype._fetchResult = function () {
  8466. this._totalAccumulated += this._current;
  8467. this._lastSecAccumulated += this._current;
  8468. // Min/Max update
  8469. this._min = Math.min(this._min, this._current);
  8470. this._max = Math.max(this._max, this._current);
  8471. this._average = this._totalAccumulated / this._totalValueCount;
  8472. // Reset last sec?
  8473. var now = Tools.Now;
  8474. if ((now - this._lastSecTime) > 1000) {
  8475. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8476. this._lastSecTime = now;
  8477. this._lastSecAccumulated = 0;
  8478. this._lastSecValueCount = 0;
  8479. }
  8480. };
  8481. PerfCounter.Enabled = true;
  8482. return PerfCounter;
  8483. }());
  8484. BABYLON.PerfCounter = PerfCounter;
  8485. /**
  8486. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8487. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8488. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8489. * @param name The name of the class, case should be preserved
  8490. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8491. */
  8492. function className(name, module) {
  8493. return function (target) {
  8494. target["__bjsclassName__"] = name;
  8495. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8496. };
  8497. }
  8498. BABYLON.className = className;
  8499. /**
  8500. * An implementation of a loop for asynchronous functions.
  8501. */
  8502. var AsyncLoop = /** @class */ (function () {
  8503. /**
  8504. * Constroctor.
  8505. * @param iterations the number of iterations.
  8506. * @param _fn the function to run each iteration
  8507. * @param _successCallback the callback that will be called upon succesful execution
  8508. * @param offset starting offset.
  8509. */
  8510. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8511. if (offset === void 0) { offset = 0; }
  8512. this.iterations = iterations;
  8513. this._fn = _fn;
  8514. this._successCallback = _successCallback;
  8515. this.index = offset - 1;
  8516. this._done = false;
  8517. }
  8518. /**
  8519. * Execute the next iteration. Must be called after the last iteration was finished.
  8520. */
  8521. AsyncLoop.prototype.executeNext = function () {
  8522. if (!this._done) {
  8523. if (this.index + 1 < this.iterations) {
  8524. ++this.index;
  8525. this._fn(this);
  8526. }
  8527. else {
  8528. this.breakLoop();
  8529. }
  8530. }
  8531. };
  8532. /**
  8533. * Break the loop and run the success callback.
  8534. */
  8535. AsyncLoop.prototype.breakLoop = function () {
  8536. this._done = true;
  8537. this._successCallback();
  8538. };
  8539. /**
  8540. * Helper function
  8541. */
  8542. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8543. if (offset === void 0) { offset = 0; }
  8544. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8545. loop.executeNext();
  8546. return loop;
  8547. };
  8548. /**
  8549. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8550. * @param iterations total number of iterations
  8551. * @param syncedIterations number of synchronous iterations in each async iteration.
  8552. * @param fn the function to call each iteration.
  8553. * @param callback a success call back that will be called when iterating stops.
  8554. * @param breakFunction a break condition (optional)
  8555. * @param timeout timeout settings for the setTimeout function. default - 0.
  8556. * @constructor
  8557. */
  8558. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8559. if (timeout === void 0) { timeout = 0; }
  8560. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8561. if (breakFunction && breakFunction())
  8562. loop.breakLoop();
  8563. else {
  8564. setTimeout(function () {
  8565. for (var i = 0; i < syncedIterations; ++i) {
  8566. var iteration = (loop.index * syncedIterations) + i;
  8567. if (iteration >= iterations)
  8568. break;
  8569. fn(iteration);
  8570. if (breakFunction && breakFunction()) {
  8571. loop.breakLoop();
  8572. break;
  8573. }
  8574. }
  8575. loop.executeNext();
  8576. }, timeout);
  8577. }
  8578. }, callback);
  8579. };
  8580. return AsyncLoop;
  8581. }());
  8582. BABYLON.AsyncLoop = AsyncLoop;
  8583. })(BABYLON || (BABYLON = {}));
  8584. //# sourceMappingURL=babylon.tools.js.map
  8585. var BABYLON;
  8586. (function (BABYLON) {
  8587. var PromiseStates;
  8588. (function (PromiseStates) {
  8589. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  8590. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  8591. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  8592. })(PromiseStates || (PromiseStates = {}));
  8593. var FulFillmentAgregator = /** @class */ (function () {
  8594. function FulFillmentAgregator() {
  8595. this.count = 0;
  8596. this.target = 0;
  8597. this.results = [];
  8598. }
  8599. return FulFillmentAgregator;
  8600. }());
  8601. var InternalPromise = /** @class */ (function () {
  8602. function InternalPromise(resolver) {
  8603. var _this = this;
  8604. this._state = PromiseStates.Pending;
  8605. this._children = new Array();
  8606. this._rejectWasConsumed = false;
  8607. if (!resolver) {
  8608. return;
  8609. }
  8610. try {
  8611. resolver(function (value) {
  8612. _this._resolve(value);
  8613. }, function (reason) {
  8614. _this._reject(reason);
  8615. });
  8616. }
  8617. catch (e) {
  8618. this._reject(e.message);
  8619. }
  8620. }
  8621. Object.defineProperty(InternalPromise.prototype, "state", {
  8622. get: function () {
  8623. return this._state;
  8624. },
  8625. enumerable: true,
  8626. configurable: true
  8627. });
  8628. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  8629. get: function () {
  8630. return this._state === PromiseStates.Fulfilled;
  8631. },
  8632. enumerable: true,
  8633. configurable: true
  8634. });
  8635. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  8636. get: function () {
  8637. return this._state === PromiseStates.Rejected;
  8638. },
  8639. enumerable: true,
  8640. configurable: true
  8641. });
  8642. Object.defineProperty(InternalPromise.prototype, "isPending", {
  8643. get: function () {
  8644. return this._state === PromiseStates.Pending;
  8645. },
  8646. enumerable: true,
  8647. configurable: true
  8648. });
  8649. InternalPromise.prototype.value = function () {
  8650. if (!this.isFulfilled) {
  8651. throw new Error("Promise is not fulfilled");
  8652. }
  8653. return this._result;
  8654. };
  8655. InternalPromise.prototype.reason = function () {
  8656. if (!this.isRejected) {
  8657. throw new Error("Promise is not rejected");
  8658. }
  8659. return this._reason;
  8660. };
  8661. InternalPromise.prototype.catch = function (onRejected) {
  8662. return this.then(undefined, onRejected);
  8663. };
  8664. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  8665. var newPromise = new InternalPromise();
  8666. newPromise._onFulfilled = onFulfilled;
  8667. newPromise._onRejected = onRejected;
  8668. // Composition
  8669. this._children.push(newPromise);
  8670. if (this._state !== PromiseStates.Pending) {
  8671. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  8672. var returnedValue = newPromise._resolve(this._result);
  8673. if (returnedValue !== undefined && returnedValue !== null) {
  8674. if (returnedValue._state !== undefined) {
  8675. var returnedPromise = returnedValue;
  8676. newPromise._children.push(returnedPromise);
  8677. newPromise = returnedPromise;
  8678. }
  8679. else {
  8680. newPromise._result = returnedValue;
  8681. }
  8682. }
  8683. }
  8684. else {
  8685. newPromise._reject(this._reason);
  8686. }
  8687. }
  8688. return newPromise;
  8689. };
  8690. InternalPromise.prototype._moveChildren = function (children) {
  8691. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  8692. if (this.isFulfilled) {
  8693. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  8694. var child = _b[_i];
  8695. child._resolve(this._result);
  8696. }
  8697. }
  8698. else if (this.isRejected) {
  8699. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  8700. var child = _d[_c];
  8701. child._reject(this._reason);
  8702. }
  8703. }
  8704. var _a;
  8705. };
  8706. InternalPromise.prototype._resolve = function (value) {
  8707. try {
  8708. this._state = PromiseStates.Fulfilled;
  8709. this._result = value;
  8710. var returnedValue = null;
  8711. if (this._onFulfilled) {
  8712. returnedValue = this._onFulfilled(value);
  8713. }
  8714. if (returnedValue !== undefined && returnedValue !== null) {
  8715. if (returnedValue._state !== undefined) {
  8716. // Transmit children
  8717. var returnedPromise = returnedValue;
  8718. returnedPromise._moveChildren(this._children);
  8719. }
  8720. else {
  8721. value = returnedValue;
  8722. }
  8723. }
  8724. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8725. var child = _a[_i];
  8726. child._resolve(value);
  8727. }
  8728. return returnedValue;
  8729. }
  8730. catch (e) {
  8731. this._reject(e.message);
  8732. }
  8733. return null;
  8734. };
  8735. InternalPromise.prototype._reject = function (reason) {
  8736. this._state = PromiseStates.Rejected;
  8737. this._reason = reason;
  8738. if (this._onRejected) {
  8739. this._onRejected(reason);
  8740. this._rejectWasConsumed = true;
  8741. }
  8742. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8743. var child = _a[_i];
  8744. if (this._rejectWasConsumed) {
  8745. child._resolve(null);
  8746. }
  8747. else {
  8748. child._reject(reason);
  8749. }
  8750. }
  8751. };
  8752. InternalPromise.resolve = function (value) {
  8753. var newPromise = new InternalPromise();
  8754. newPromise._resolve(value);
  8755. return newPromise;
  8756. };
  8757. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  8758. promise.then(function (value) {
  8759. agregator.results[index] = value;
  8760. agregator.count++;
  8761. if (agregator.count === agregator.target) {
  8762. agregator.rootPromise._resolve(agregator.results);
  8763. }
  8764. return null;
  8765. }, function (reason) {
  8766. if (!agregator.rootPromise.isRejected) {
  8767. agregator.rootPromise._reject(reason);
  8768. }
  8769. });
  8770. };
  8771. InternalPromise.all = function (promises) {
  8772. var newPromise = new InternalPromise();
  8773. var agregator = new FulFillmentAgregator();
  8774. agregator.target = promises.length;
  8775. agregator.rootPromise = newPromise;
  8776. if (promises.length) {
  8777. for (var index = 0; index < promises.length; index++) {
  8778. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  8779. }
  8780. }
  8781. else {
  8782. newPromise._resolve([]);
  8783. }
  8784. return newPromise;
  8785. };
  8786. return InternalPromise;
  8787. }());
  8788. /**
  8789. * Helper class that provides a small promise polyfill
  8790. */
  8791. var PromisePolyfill = /** @class */ (function () {
  8792. function PromisePolyfill() {
  8793. }
  8794. /**
  8795. * Static function used to check if the polyfill is required
  8796. * If this is the case then the function will inject the polyfill to window.Promise
  8797. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  8798. */
  8799. PromisePolyfill.Apply = function (force) {
  8800. if (force === void 0) { force = false; }
  8801. if (force || typeof Promise === 'undefined') {
  8802. var root = window;
  8803. root.Promise = InternalPromise;
  8804. }
  8805. };
  8806. return PromisePolyfill;
  8807. }());
  8808. BABYLON.PromisePolyfill = PromisePolyfill;
  8809. })(BABYLON || (BABYLON = {}));
  8810. //# sourceMappingURL=babylon.promise.js.map
  8811. var BABYLON;
  8812. (function (BABYLON) {
  8813. var _AlphaState = /** @class */ (function () {
  8814. /**
  8815. * Initializes the state.
  8816. */
  8817. function _AlphaState() {
  8818. this._isAlphaBlendDirty = false;
  8819. this._isBlendFunctionParametersDirty = false;
  8820. this._isBlendEquationParametersDirty = false;
  8821. this._isBlendConstantsDirty = false;
  8822. this._alphaBlend = false;
  8823. this._blendFunctionParameters = new Array(4);
  8824. this._blendEquationParameters = new Array(2);
  8825. this._blendConstants = new Array(4);
  8826. this.reset();
  8827. }
  8828. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8829. get: function () {
  8830. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8831. },
  8832. enumerable: true,
  8833. configurable: true
  8834. });
  8835. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8836. get: function () {
  8837. return this._alphaBlend;
  8838. },
  8839. set: function (value) {
  8840. if (this._alphaBlend === value) {
  8841. return;
  8842. }
  8843. this._alphaBlend = value;
  8844. this._isAlphaBlendDirty = true;
  8845. },
  8846. enumerable: true,
  8847. configurable: true
  8848. });
  8849. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8850. if (this._blendConstants[0] === r &&
  8851. this._blendConstants[1] === g &&
  8852. this._blendConstants[2] === b &&
  8853. this._blendConstants[3] === a) {
  8854. return;
  8855. }
  8856. this._blendConstants[0] = r;
  8857. this._blendConstants[1] = g;
  8858. this._blendConstants[2] = b;
  8859. this._blendConstants[3] = a;
  8860. this._isBlendConstantsDirty = true;
  8861. };
  8862. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8863. if (this._blendFunctionParameters[0] === value0 &&
  8864. this._blendFunctionParameters[1] === value1 &&
  8865. this._blendFunctionParameters[2] === value2 &&
  8866. this._blendFunctionParameters[3] === value3) {
  8867. return;
  8868. }
  8869. this._blendFunctionParameters[0] = value0;
  8870. this._blendFunctionParameters[1] = value1;
  8871. this._blendFunctionParameters[2] = value2;
  8872. this._blendFunctionParameters[3] = value3;
  8873. this._isBlendFunctionParametersDirty = true;
  8874. };
  8875. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8876. if (this._blendEquationParameters[0] === rgb &&
  8877. this._blendEquationParameters[1] === alpha) {
  8878. return;
  8879. }
  8880. this._blendEquationParameters[0] = rgb;
  8881. this._blendEquationParameters[1] = alpha;
  8882. this._isBlendEquationParametersDirty = true;
  8883. };
  8884. _AlphaState.prototype.reset = function () {
  8885. this._alphaBlend = false;
  8886. this._blendFunctionParameters[0] = null;
  8887. this._blendFunctionParameters[1] = null;
  8888. this._blendFunctionParameters[2] = null;
  8889. this._blendFunctionParameters[3] = null;
  8890. this._blendEquationParameters[0] = null;
  8891. this._blendEquationParameters[1] = null;
  8892. this._blendConstants[0] = null;
  8893. this._blendConstants[1] = null;
  8894. this._blendConstants[2] = null;
  8895. this._blendConstants[3] = null;
  8896. this._isAlphaBlendDirty = true;
  8897. this._isBlendFunctionParametersDirty = false;
  8898. this._isBlendEquationParametersDirty = false;
  8899. this._isBlendConstantsDirty = false;
  8900. };
  8901. _AlphaState.prototype.apply = function (gl) {
  8902. if (!this.isDirty) {
  8903. return;
  8904. }
  8905. // Alpha blend
  8906. if (this._isAlphaBlendDirty) {
  8907. if (this._alphaBlend) {
  8908. gl.enable(gl.BLEND);
  8909. }
  8910. else {
  8911. gl.disable(gl.BLEND);
  8912. }
  8913. this._isAlphaBlendDirty = false;
  8914. }
  8915. // Alpha function
  8916. if (this._isBlendFunctionParametersDirty) {
  8917. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8918. this._isBlendFunctionParametersDirty = false;
  8919. }
  8920. // Alpha equation
  8921. if (this._isBlendEquationParametersDirty) {
  8922. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8923. this._isBlendEquationParametersDirty = false;
  8924. }
  8925. // Constants
  8926. if (this._isBlendConstantsDirty) {
  8927. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8928. this._isBlendConstantsDirty = false;
  8929. }
  8930. };
  8931. return _AlphaState;
  8932. }());
  8933. BABYLON._AlphaState = _AlphaState;
  8934. })(BABYLON || (BABYLON = {}));
  8935. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8936. var BABYLON;
  8937. (function (BABYLON) {
  8938. var _DepthCullingState = /** @class */ (function () {
  8939. /**
  8940. * Initializes the state.
  8941. */
  8942. function _DepthCullingState() {
  8943. this._isDepthTestDirty = false;
  8944. this._isDepthMaskDirty = false;
  8945. this._isDepthFuncDirty = false;
  8946. this._isCullFaceDirty = false;
  8947. this._isCullDirty = false;
  8948. this._isZOffsetDirty = false;
  8949. this._isFrontFaceDirty = false;
  8950. this.reset();
  8951. }
  8952. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8953. get: function () {
  8954. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8955. },
  8956. enumerable: true,
  8957. configurable: true
  8958. });
  8959. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8960. get: function () {
  8961. return this._zOffset;
  8962. },
  8963. set: function (value) {
  8964. if (this._zOffset === value) {
  8965. return;
  8966. }
  8967. this._zOffset = value;
  8968. this._isZOffsetDirty = true;
  8969. },
  8970. enumerable: true,
  8971. configurable: true
  8972. });
  8973. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8974. get: function () {
  8975. return this._cullFace;
  8976. },
  8977. set: function (value) {
  8978. if (this._cullFace === value) {
  8979. return;
  8980. }
  8981. this._cullFace = value;
  8982. this._isCullFaceDirty = true;
  8983. },
  8984. enumerable: true,
  8985. configurable: true
  8986. });
  8987. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8988. get: function () {
  8989. return this._cull;
  8990. },
  8991. set: function (value) {
  8992. if (this._cull === value) {
  8993. return;
  8994. }
  8995. this._cull = value;
  8996. this._isCullDirty = true;
  8997. },
  8998. enumerable: true,
  8999. configurable: true
  9000. });
  9001. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9002. get: function () {
  9003. return this._depthFunc;
  9004. },
  9005. set: function (value) {
  9006. if (this._depthFunc === value) {
  9007. return;
  9008. }
  9009. this._depthFunc = value;
  9010. this._isDepthFuncDirty = true;
  9011. },
  9012. enumerable: true,
  9013. configurable: true
  9014. });
  9015. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9016. get: function () {
  9017. return this._depthMask;
  9018. },
  9019. set: function (value) {
  9020. if (this._depthMask === value) {
  9021. return;
  9022. }
  9023. this._depthMask = value;
  9024. this._isDepthMaskDirty = true;
  9025. },
  9026. enumerable: true,
  9027. configurable: true
  9028. });
  9029. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9030. get: function () {
  9031. return this._depthTest;
  9032. },
  9033. set: function (value) {
  9034. if (this._depthTest === value) {
  9035. return;
  9036. }
  9037. this._depthTest = value;
  9038. this._isDepthTestDirty = true;
  9039. },
  9040. enumerable: true,
  9041. configurable: true
  9042. });
  9043. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9044. get: function () {
  9045. return this._frontFace;
  9046. },
  9047. set: function (value) {
  9048. if (this._frontFace === value) {
  9049. return;
  9050. }
  9051. this._frontFace = value;
  9052. this._isFrontFaceDirty = true;
  9053. },
  9054. enumerable: true,
  9055. configurable: true
  9056. });
  9057. _DepthCullingState.prototype.reset = function () {
  9058. this._depthMask = true;
  9059. this._depthTest = true;
  9060. this._depthFunc = null;
  9061. this._cullFace = null;
  9062. this._cull = null;
  9063. this._zOffset = 0;
  9064. this._frontFace = null;
  9065. this._isDepthTestDirty = true;
  9066. this._isDepthMaskDirty = true;
  9067. this._isDepthFuncDirty = false;
  9068. this._isCullFaceDirty = false;
  9069. this._isCullDirty = false;
  9070. this._isZOffsetDirty = false;
  9071. this._isFrontFaceDirty = false;
  9072. };
  9073. _DepthCullingState.prototype.apply = function (gl) {
  9074. if (!this.isDirty) {
  9075. return;
  9076. }
  9077. // Cull
  9078. if (this._isCullDirty) {
  9079. if (this.cull) {
  9080. gl.enable(gl.CULL_FACE);
  9081. }
  9082. else {
  9083. gl.disable(gl.CULL_FACE);
  9084. }
  9085. this._isCullDirty = false;
  9086. }
  9087. // Cull face
  9088. if (this._isCullFaceDirty) {
  9089. gl.cullFace(this.cullFace);
  9090. this._isCullFaceDirty = false;
  9091. }
  9092. // Depth mask
  9093. if (this._isDepthMaskDirty) {
  9094. gl.depthMask(this.depthMask);
  9095. this._isDepthMaskDirty = false;
  9096. }
  9097. // Depth test
  9098. if (this._isDepthTestDirty) {
  9099. if (this.depthTest) {
  9100. gl.enable(gl.DEPTH_TEST);
  9101. }
  9102. else {
  9103. gl.disable(gl.DEPTH_TEST);
  9104. }
  9105. this._isDepthTestDirty = false;
  9106. }
  9107. // Depth func
  9108. if (this._isDepthFuncDirty) {
  9109. gl.depthFunc(this.depthFunc);
  9110. this._isDepthFuncDirty = false;
  9111. }
  9112. // zOffset
  9113. if (this._isZOffsetDirty) {
  9114. if (this.zOffset) {
  9115. gl.enable(gl.POLYGON_OFFSET_FILL);
  9116. gl.polygonOffset(this.zOffset, 0);
  9117. }
  9118. else {
  9119. gl.disable(gl.POLYGON_OFFSET_FILL);
  9120. }
  9121. this._isZOffsetDirty = false;
  9122. }
  9123. // Front face
  9124. if (this._isFrontFaceDirty) {
  9125. gl.frontFace(this.frontFace);
  9126. this._isFrontFaceDirty = false;
  9127. }
  9128. };
  9129. return _DepthCullingState;
  9130. }());
  9131. BABYLON._DepthCullingState = _DepthCullingState;
  9132. })(BABYLON || (BABYLON = {}));
  9133. //# sourceMappingURL=babylon.depthCullingState.js.map
  9134. var BABYLON;
  9135. (function (BABYLON) {
  9136. var _StencilState = /** @class */ (function () {
  9137. function _StencilState() {
  9138. this._isStencilTestDirty = false;
  9139. this._isStencilMaskDirty = false;
  9140. this._isStencilFuncDirty = false;
  9141. this._isStencilOpDirty = false;
  9142. this.reset();
  9143. }
  9144. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9145. get: function () {
  9146. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9147. },
  9148. enumerable: true,
  9149. configurable: true
  9150. });
  9151. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9152. get: function () {
  9153. return this._stencilFunc;
  9154. },
  9155. set: function (value) {
  9156. if (this._stencilFunc === value) {
  9157. return;
  9158. }
  9159. this._stencilFunc = value;
  9160. this._isStencilFuncDirty = true;
  9161. },
  9162. enumerable: true,
  9163. configurable: true
  9164. });
  9165. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9166. get: function () {
  9167. return this._stencilFuncRef;
  9168. },
  9169. set: function (value) {
  9170. if (this._stencilFuncRef === value) {
  9171. return;
  9172. }
  9173. this._stencilFuncRef = value;
  9174. this._isStencilFuncDirty = true;
  9175. },
  9176. enumerable: true,
  9177. configurable: true
  9178. });
  9179. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9180. get: function () {
  9181. return this._stencilFuncMask;
  9182. },
  9183. set: function (value) {
  9184. if (this._stencilFuncMask === value) {
  9185. return;
  9186. }
  9187. this._stencilFuncMask = value;
  9188. this._isStencilFuncDirty = true;
  9189. },
  9190. enumerable: true,
  9191. configurable: true
  9192. });
  9193. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9194. get: function () {
  9195. return this._stencilOpStencilFail;
  9196. },
  9197. set: function (value) {
  9198. if (this._stencilOpStencilFail === value) {
  9199. return;
  9200. }
  9201. this._stencilOpStencilFail = value;
  9202. this._isStencilOpDirty = true;
  9203. },
  9204. enumerable: true,
  9205. configurable: true
  9206. });
  9207. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9208. get: function () {
  9209. return this._stencilOpDepthFail;
  9210. },
  9211. set: function (value) {
  9212. if (this._stencilOpDepthFail === value) {
  9213. return;
  9214. }
  9215. this._stencilOpDepthFail = value;
  9216. this._isStencilOpDirty = true;
  9217. },
  9218. enumerable: true,
  9219. configurable: true
  9220. });
  9221. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9222. get: function () {
  9223. return this._stencilOpStencilDepthPass;
  9224. },
  9225. set: function (value) {
  9226. if (this._stencilOpStencilDepthPass === value) {
  9227. return;
  9228. }
  9229. this._stencilOpStencilDepthPass = value;
  9230. this._isStencilOpDirty = true;
  9231. },
  9232. enumerable: true,
  9233. configurable: true
  9234. });
  9235. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9236. get: function () {
  9237. return this._stencilMask;
  9238. },
  9239. set: function (value) {
  9240. if (this._stencilMask === value) {
  9241. return;
  9242. }
  9243. this._stencilMask = value;
  9244. this._isStencilMaskDirty = true;
  9245. },
  9246. enumerable: true,
  9247. configurable: true
  9248. });
  9249. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9250. get: function () {
  9251. return this._stencilTest;
  9252. },
  9253. set: function (value) {
  9254. if (this._stencilTest === value) {
  9255. return;
  9256. }
  9257. this._stencilTest = value;
  9258. this._isStencilTestDirty = true;
  9259. },
  9260. enumerable: true,
  9261. configurable: true
  9262. });
  9263. _StencilState.prototype.reset = function () {
  9264. this._stencilTest = false;
  9265. this._stencilMask = 0xFF;
  9266. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9267. this._stencilFuncRef = 1;
  9268. this._stencilFuncMask = 0xFF;
  9269. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9270. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9271. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9272. this._isStencilTestDirty = true;
  9273. this._isStencilMaskDirty = true;
  9274. this._isStencilFuncDirty = true;
  9275. this._isStencilOpDirty = true;
  9276. };
  9277. _StencilState.prototype.apply = function (gl) {
  9278. if (!this.isDirty) {
  9279. return;
  9280. }
  9281. // Stencil test
  9282. if (this._isStencilTestDirty) {
  9283. if (this.stencilTest) {
  9284. gl.enable(gl.STENCIL_TEST);
  9285. }
  9286. else {
  9287. gl.disable(gl.STENCIL_TEST);
  9288. }
  9289. this._isStencilTestDirty = false;
  9290. }
  9291. // Stencil mask
  9292. if (this._isStencilMaskDirty) {
  9293. gl.stencilMask(this.stencilMask);
  9294. this._isStencilMaskDirty = false;
  9295. }
  9296. // Stencil func
  9297. if (this._isStencilFuncDirty) {
  9298. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9299. this._isStencilFuncDirty = false;
  9300. }
  9301. // Stencil op
  9302. if (this._isStencilOpDirty) {
  9303. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9304. this._isStencilOpDirty = false;
  9305. }
  9306. };
  9307. return _StencilState;
  9308. }());
  9309. BABYLON._StencilState = _StencilState;
  9310. })(BABYLON || (BABYLON = {}));
  9311. //# sourceMappingURL=babylon.stencilState.js.map
  9312. var BABYLON;
  9313. (function (BABYLON) {
  9314. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9315. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9316. };
  9317. var compileRawShader = function (gl, source, type) {
  9318. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9319. gl.shaderSource(shader, source);
  9320. gl.compileShader(shader);
  9321. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9322. var log = gl.getShaderInfoLog(shader);
  9323. if (log) {
  9324. throw new Error(log);
  9325. }
  9326. }
  9327. if (!shader) {
  9328. throw new Error("Something went wrong while compile the shader.");
  9329. }
  9330. return shader;
  9331. };
  9332. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9333. var magFilter = gl.NEAREST;
  9334. var minFilter = gl.NEAREST;
  9335. switch (samplingMode) {
  9336. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9337. magFilter = gl.LINEAR;
  9338. if (generateMipMaps) {
  9339. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9340. }
  9341. else {
  9342. minFilter = gl.LINEAR;
  9343. }
  9344. break;
  9345. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9346. magFilter = gl.LINEAR;
  9347. if (generateMipMaps) {
  9348. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9349. }
  9350. else {
  9351. minFilter = gl.LINEAR;
  9352. }
  9353. break;
  9354. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9355. magFilter = gl.NEAREST;
  9356. if (generateMipMaps) {
  9357. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9358. }
  9359. else {
  9360. minFilter = gl.NEAREST;
  9361. }
  9362. break;
  9363. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  9364. magFilter = gl.NEAREST;
  9365. if (generateMipMaps) {
  9366. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9367. }
  9368. else {
  9369. minFilter = gl.NEAREST;
  9370. }
  9371. break;
  9372. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  9373. magFilter = gl.NEAREST;
  9374. if (generateMipMaps) {
  9375. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9376. }
  9377. else {
  9378. minFilter = gl.LINEAR;
  9379. }
  9380. break;
  9381. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  9382. magFilter = gl.NEAREST;
  9383. if (generateMipMaps) {
  9384. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9385. }
  9386. else {
  9387. minFilter = gl.LINEAR;
  9388. }
  9389. break;
  9390. case BABYLON.Texture.NEAREST_LINEAR:
  9391. magFilter = gl.NEAREST;
  9392. minFilter = gl.LINEAR;
  9393. break;
  9394. case BABYLON.Texture.NEAREST_NEAREST:
  9395. magFilter = gl.NEAREST;
  9396. minFilter = gl.NEAREST;
  9397. break;
  9398. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  9399. magFilter = gl.LINEAR;
  9400. if (generateMipMaps) {
  9401. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9402. }
  9403. else {
  9404. minFilter = gl.NEAREST;
  9405. }
  9406. break;
  9407. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  9408. magFilter = gl.LINEAR;
  9409. if (generateMipMaps) {
  9410. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9411. }
  9412. else {
  9413. minFilter = gl.NEAREST;
  9414. }
  9415. break;
  9416. case BABYLON.Texture.LINEAR_LINEAR:
  9417. magFilter = gl.LINEAR;
  9418. minFilter = gl.LINEAR;
  9419. break;
  9420. case BABYLON.Texture.LINEAR_NEAREST:
  9421. magFilter = gl.LINEAR;
  9422. minFilter = gl.NEAREST;
  9423. break;
  9424. }
  9425. return {
  9426. min: minFilter,
  9427. mag: magFilter
  9428. };
  9429. };
  9430. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  9431. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  9432. var img;
  9433. var onload = function () {
  9434. loadedImages[index] = img;
  9435. loadedImages._internalCount++;
  9436. if (scene) {
  9437. scene._removePendingData(img);
  9438. }
  9439. if (loadedImages._internalCount === 6) {
  9440. onfinish(loadedImages);
  9441. }
  9442. };
  9443. var onerror = function (message, exception) {
  9444. if (scene) {
  9445. scene._removePendingData(img);
  9446. }
  9447. if (onErrorCallBack) {
  9448. onErrorCallBack(message, exception);
  9449. }
  9450. };
  9451. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9452. if (scene) {
  9453. scene._addPendingData(img);
  9454. }
  9455. };
  9456. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  9457. if (onError === void 0) { onError = null; }
  9458. var loadedImages = [];
  9459. loadedImages._internalCount = 0;
  9460. for (var index = 0; index < 6; index++) {
  9461. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  9462. }
  9463. };
  9464. var BufferPointer = /** @class */ (function () {
  9465. function BufferPointer() {
  9466. }
  9467. return BufferPointer;
  9468. }());
  9469. var InstancingAttributeInfo = /** @class */ (function () {
  9470. function InstancingAttributeInfo() {
  9471. }
  9472. return InstancingAttributeInfo;
  9473. }());
  9474. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  9475. /**
  9476. * Define options used to create a render target texture
  9477. */
  9478. var RenderTargetCreationOptions = /** @class */ (function () {
  9479. function RenderTargetCreationOptions() {
  9480. }
  9481. return RenderTargetCreationOptions;
  9482. }());
  9483. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  9484. /**
  9485. * Regroup several parameters relative to the browser in use
  9486. */
  9487. var EngineCapabilities = /** @class */ (function () {
  9488. function EngineCapabilities() {
  9489. }
  9490. return EngineCapabilities;
  9491. }());
  9492. BABYLON.EngineCapabilities = EngineCapabilities;
  9493. /**
  9494. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  9495. */
  9496. var Engine = /** @class */ (function () {
  9497. /**
  9498. * @constructor
  9499. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  9500. * @param antialias defines enable antialiasing (default: false)
  9501. * @param options defines further options to be sent to the getContext() function
  9502. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  9503. */
  9504. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  9505. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  9506. var _this = this;
  9507. // Public members
  9508. this.forcePOTTextures = false;
  9509. this.isFullscreen = false;
  9510. this.isPointerLock = false;
  9511. this.cullBackFaces = true;
  9512. this.renderEvenInBackground = true;
  9513. this.preventCacheWipeBetweenFrames = false;
  9514. // To enable/disable IDB support and avoid XHR on .manifest
  9515. this.enableOfflineSupport = false;
  9516. this.scenes = new Array();
  9517. this.postProcesses = new Array();
  9518. // Observables
  9519. /**
  9520. * Observable event triggered each time the rendering canvas is resized
  9521. */
  9522. this.onResizeObservable = new BABYLON.Observable();
  9523. /**
  9524. * Observable event triggered each time the canvas loses focus
  9525. */
  9526. this.onCanvasBlurObservable = new BABYLON.Observable();
  9527. /**
  9528. * Observable event triggered each time the canvas gains focus
  9529. */
  9530. this.onCanvasFocusObservable = new BABYLON.Observable();
  9531. /**
  9532. * Observable event triggered each time the canvas receives pointerout event
  9533. */
  9534. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  9535. /**
  9536. * Observable event triggered before each texture is initialized
  9537. */
  9538. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  9539. //WebVR
  9540. this._vrDisplay = undefined;
  9541. this._vrSupported = false;
  9542. this._vrExclusivePointerMode = false;
  9543. // Uniform buffers list
  9544. this.disableUniformBuffers = false;
  9545. this._uniformBuffers = new Array();
  9546. // Observables
  9547. /**
  9548. * Observable raised when the engine begins a new frame
  9549. */
  9550. this.onBeginFrameObservable = new BABYLON.Observable();
  9551. /**
  9552. * Observable raised when the engine ends the current frame
  9553. */
  9554. this.onEndFrameObservable = new BABYLON.Observable();
  9555. /**
  9556. * Observable raised when the engine is about to compile a shader
  9557. */
  9558. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  9559. /**
  9560. * Observable raised when the engine has jsut compiled a shader
  9561. */
  9562. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  9563. this._windowIsBackground = false;
  9564. this._webGLVersion = 1.0;
  9565. this._badOS = false;
  9566. this._badDesktopOS = false;
  9567. /**
  9568. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9569. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9570. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9571. */
  9572. this.disableTextureBindingOptimization = false;
  9573. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9574. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9575. this.onVRRequestPresentStart = new BABYLON.Observable();
  9576. this._colorWrite = true;
  9577. this._drawCalls = new BABYLON.PerfCounter();
  9578. this._textureCollisions = new BABYLON.PerfCounter();
  9579. this._renderingQueueLaunched = false;
  9580. this._activeRenderLoops = new Array();
  9581. // Deterministic lockstepMaxSteps
  9582. this._deterministicLockstep = false;
  9583. this._lockstepMaxSteps = 4;
  9584. // Lost context
  9585. this.onContextLostObservable = new BABYLON.Observable();
  9586. this.onContextRestoredObservable = new BABYLON.Observable();
  9587. this._contextWasLost = false;
  9588. this._doNotHandleContextLost = false;
  9589. // FPS
  9590. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9591. this._fps = 60;
  9592. this._deltaTime = 0;
  9593. /**
  9594. * Turn this value on if you want to pause FPS computation when in background
  9595. */
  9596. this.disablePerformanceMonitorInBackground = false;
  9597. // States
  9598. this._depthCullingState = new BABYLON._DepthCullingState();
  9599. this._stencilState = new BABYLON._StencilState();
  9600. this._alphaState = new BABYLON._AlphaState();
  9601. this._alphaMode = Engine.ALPHA_DISABLE;
  9602. // Cache
  9603. this._internalTexturesCache = new Array();
  9604. this._activeChannel = 0;
  9605. this._currentTextureChannel = -1;
  9606. this._boundTexturesCache = {};
  9607. this._compiledEffects = {};
  9608. this._vertexAttribArraysEnabled = [];
  9609. this._uintIndicesCurrentlySet = false;
  9610. this._currentBoundBuffer = new Array();
  9611. this._currentBufferPointers = new Array();
  9612. this._currentInstanceLocations = new Array();
  9613. this._currentInstanceBuffers = new Array();
  9614. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9615. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9616. this._vaoRecordInProgress = false;
  9617. this._mustWipeVertexAttributes = false;
  9618. this._nextFreeTextureSlots = new Array();
  9619. this._maxSimultaneousTextures = 0;
  9620. this._activeRequests = new Array();
  9621. // Hardware supported Compressed Textures
  9622. this._texturesSupported = new Array();
  9623. this._onVRFullScreenTriggered = function () {
  9624. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9625. //get the old size before we change
  9626. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9627. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9628. //get the width and height, change the render size
  9629. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9630. _this.setHardwareScalingLevel(1);
  9631. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9632. }
  9633. else {
  9634. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9635. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9636. }
  9637. };
  9638. this._boundUniforms = {};
  9639. // Register promises
  9640. BABYLON.PromisePolyfill.Apply();
  9641. var canvas = null;
  9642. Engine.Instances.push(this);
  9643. if (!canvasOrContext) {
  9644. return;
  9645. }
  9646. options = options || {};
  9647. if (canvasOrContext.getContext) {
  9648. canvas = canvasOrContext;
  9649. this._renderingCanvas = canvas;
  9650. if (antialias != null) {
  9651. options.antialias = antialias;
  9652. }
  9653. if (options.deterministicLockstep === undefined) {
  9654. options.deterministicLockstep = false;
  9655. }
  9656. if (options.lockstepMaxSteps === undefined) {
  9657. options.lockstepMaxSteps = 4;
  9658. }
  9659. if (options.preserveDrawingBuffer === undefined) {
  9660. options.preserveDrawingBuffer = false;
  9661. }
  9662. if (options.audioEngine === undefined) {
  9663. options.audioEngine = true;
  9664. }
  9665. if (options.stencil === undefined) {
  9666. options.stencil = true;
  9667. }
  9668. this._deterministicLockstep = options.deterministicLockstep;
  9669. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9670. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9671. // Exceptions
  9672. if (navigator && navigator.userAgent) {
  9673. var ua = navigator.userAgent;
  9674. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9675. var exception = _a[_i];
  9676. var key = exception.key;
  9677. var targets = exception.targets;
  9678. if (ua.indexOf(key) > -1) {
  9679. if (exception.capture && exception.captureConstraint) {
  9680. var capture = exception.capture;
  9681. var constraint = exception.captureConstraint;
  9682. var regex = new RegExp(capture);
  9683. var matches = regex.exec(ua);
  9684. if (matches && matches.length > 0) {
  9685. var capturedValue = parseInt(matches[matches.length - 1]);
  9686. if (capturedValue >= constraint) {
  9687. continue;
  9688. }
  9689. }
  9690. }
  9691. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9692. var target = targets_1[_b];
  9693. switch (target) {
  9694. case "uniformBuffer":
  9695. this.disableUniformBuffers = true;
  9696. break;
  9697. case "textureBindingOptimization":
  9698. this.disableTextureBindingOptimization = true;
  9699. break;
  9700. }
  9701. }
  9702. break;
  9703. }
  9704. }
  9705. }
  9706. // GL
  9707. if (!options.disableWebGL2Support) {
  9708. try {
  9709. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9710. if (this._gl) {
  9711. this._webGLVersion = 2.0;
  9712. }
  9713. }
  9714. catch (e) {
  9715. // Do nothing
  9716. }
  9717. }
  9718. if (!this._gl) {
  9719. if (!canvas) {
  9720. throw new Error("The provided canvas is null or undefined.");
  9721. }
  9722. try {
  9723. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9724. }
  9725. catch (e) {
  9726. throw new Error("WebGL not supported");
  9727. }
  9728. }
  9729. if (!this._gl) {
  9730. throw new Error("WebGL not supported");
  9731. }
  9732. this._onCanvasFocus = function () {
  9733. _this.onCanvasFocusObservable.notifyObservers(_this);
  9734. };
  9735. this._onCanvasBlur = function () {
  9736. _this.onCanvasBlurObservable.notifyObservers(_this);
  9737. };
  9738. canvas.addEventListener("focus", this._onCanvasFocus);
  9739. canvas.addEventListener("blur", this._onCanvasBlur);
  9740. this._onBlur = function () {
  9741. if (_this.disablePerformanceMonitorInBackground) {
  9742. _this._performanceMonitor.disable();
  9743. }
  9744. _this._windowIsBackground = true;
  9745. };
  9746. this._onFocus = function () {
  9747. if (_this.disablePerformanceMonitorInBackground) {
  9748. _this._performanceMonitor.enable();
  9749. }
  9750. _this._windowIsBackground = false;
  9751. };
  9752. this._onCanvasPointerOut = function () {
  9753. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9754. };
  9755. window.addEventListener("blur", this._onBlur);
  9756. window.addEventListener("focus", this._onFocus);
  9757. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9758. // Context lost
  9759. if (!this._doNotHandleContextLost) {
  9760. this._onContextLost = function (evt) {
  9761. evt.preventDefault();
  9762. _this._contextWasLost = true;
  9763. BABYLON.Tools.Warn("WebGL context lost.");
  9764. _this.onContextLostObservable.notifyObservers(_this);
  9765. };
  9766. this._onContextRestored = function (evt) {
  9767. // Adding a timeout to avoid race condition at browser level
  9768. setTimeout(function () {
  9769. // Rebuild gl context
  9770. _this._initGLContext();
  9771. // Rebuild effects
  9772. _this._rebuildEffects();
  9773. // Rebuild textures
  9774. _this._rebuildInternalTextures();
  9775. // Rebuild buffers
  9776. _this._rebuildBuffers();
  9777. // Cache
  9778. _this.wipeCaches(true);
  9779. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9780. _this.onContextRestoredObservable.notifyObservers(_this);
  9781. _this._contextWasLost = false;
  9782. }, 0);
  9783. };
  9784. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9785. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9786. }
  9787. }
  9788. else {
  9789. this._gl = canvasOrContext;
  9790. this._renderingCanvas = this._gl.canvas;
  9791. if (this._gl.renderbufferStorageMultisample) {
  9792. this._webGLVersion = 2.0;
  9793. }
  9794. options.stencil = this._gl.getContextAttributes().stencil;
  9795. }
  9796. // Viewport
  9797. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9798. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9799. this.resize();
  9800. this._isStencilEnable = options.stencil ? true : false;
  9801. this._initGLContext();
  9802. if (canvas) {
  9803. // Fullscreen
  9804. this._onFullscreenChange = function () {
  9805. if (document.fullscreen !== undefined) {
  9806. _this.isFullscreen = document.fullscreen;
  9807. }
  9808. else if (document.mozFullScreen !== undefined) {
  9809. _this.isFullscreen = document.mozFullScreen;
  9810. }
  9811. else if (document.webkitIsFullScreen !== undefined) {
  9812. _this.isFullscreen = document.webkitIsFullScreen;
  9813. }
  9814. else if (document.msIsFullScreen !== undefined) {
  9815. _this.isFullscreen = document.msIsFullScreen;
  9816. }
  9817. // Pointer lock
  9818. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9819. canvas.requestPointerLock = canvas.requestPointerLock ||
  9820. canvas.msRequestPointerLock ||
  9821. canvas.mozRequestPointerLock ||
  9822. canvas.webkitRequestPointerLock;
  9823. if (canvas.requestPointerLock) {
  9824. canvas.requestPointerLock();
  9825. }
  9826. }
  9827. };
  9828. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9829. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9830. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9831. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9832. // Pointer lock
  9833. this._onPointerLockChange = function () {
  9834. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9835. document.webkitPointerLockElement === canvas ||
  9836. document.msPointerLockElement === canvas ||
  9837. document.pointerLockElement === canvas);
  9838. };
  9839. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9840. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9841. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9842. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9843. this._onVRDisplayPointerRestricted = function () {
  9844. if (canvas) {
  9845. canvas.requestPointerLock();
  9846. }
  9847. };
  9848. this._onVRDisplayPointerUnrestricted = function () {
  9849. document.exitPointerLock();
  9850. };
  9851. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9852. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9853. }
  9854. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9855. Engine.audioEngine = new BABYLON.AudioEngine();
  9856. }
  9857. // Prepare buffer pointers
  9858. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9859. this._currentBufferPointers[i] = new BufferPointer();
  9860. }
  9861. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9862. // Load WebVR Devices
  9863. if (options.autoEnableWebVR) {
  9864. this.initWebVR();
  9865. }
  9866. // Detect if we are running on a faulty buggy OS.
  9867. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9868. // Detect if we are running on a faulty buggy desktop OS.
  9869. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9870. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9871. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9872. }
  9873. Object.defineProperty(Engine, "LastCreatedEngine", {
  9874. get: function () {
  9875. if (Engine.Instances.length === 0) {
  9876. return null;
  9877. }
  9878. return Engine.Instances[Engine.Instances.length - 1];
  9879. },
  9880. enumerable: true,
  9881. configurable: true
  9882. });
  9883. Object.defineProperty(Engine, "LastCreatedScene", {
  9884. get: function () {
  9885. var lastCreatedEngine = Engine.LastCreatedEngine;
  9886. if (!lastCreatedEngine) {
  9887. return null;
  9888. }
  9889. if (lastCreatedEngine.scenes.length === 0) {
  9890. return null;
  9891. }
  9892. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9893. },
  9894. enumerable: true,
  9895. configurable: true
  9896. });
  9897. /**
  9898. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9899. */
  9900. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9901. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9902. var engine = Engine.Instances[engineIndex];
  9903. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9904. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9905. }
  9906. }
  9907. };
  9908. Object.defineProperty(Engine, "NEVER", {
  9909. get: function () {
  9910. return Engine._NEVER;
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. Object.defineProperty(Engine, "ALWAYS", {
  9916. get: function () {
  9917. return Engine._ALWAYS;
  9918. },
  9919. enumerable: true,
  9920. configurable: true
  9921. });
  9922. Object.defineProperty(Engine, "LESS", {
  9923. get: function () {
  9924. return Engine._LESS;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(Engine, "EQUAL", {
  9930. get: function () {
  9931. return Engine._EQUAL;
  9932. },
  9933. enumerable: true,
  9934. configurable: true
  9935. });
  9936. Object.defineProperty(Engine, "LEQUAL", {
  9937. get: function () {
  9938. return Engine._LEQUAL;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(Engine, "GREATER", {
  9944. get: function () {
  9945. return Engine._GREATER;
  9946. },
  9947. enumerable: true,
  9948. configurable: true
  9949. });
  9950. Object.defineProperty(Engine, "GEQUAL", {
  9951. get: function () {
  9952. return Engine._GEQUAL;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(Engine, "NOTEQUAL", {
  9958. get: function () {
  9959. return Engine._NOTEQUAL;
  9960. },
  9961. enumerable: true,
  9962. configurable: true
  9963. });
  9964. Object.defineProperty(Engine, "KEEP", {
  9965. get: function () {
  9966. return Engine._KEEP;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(Engine, "REPLACE", {
  9972. get: function () {
  9973. return Engine._REPLACE;
  9974. },
  9975. enumerable: true,
  9976. configurable: true
  9977. });
  9978. Object.defineProperty(Engine, "INCR", {
  9979. get: function () {
  9980. return Engine._INCR;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. Object.defineProperty(Engine, "DECR", {
  9986. get: function () {
  9987. return Engine._DECR;
  9988. },
  9989. enumerable: true,
  9990. configurable: true
  9991. });
  9992. Object.defineProperty(Engine, "INVERT", {
  9993. get: function () {
  9994. return Engine._INVERT;
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. Object.defineProperty(Engine, "INCR_WRAP", {
  10000. get: function () {
  10001. return Engine._INCR_WRAP;
  10002. },
  10003. enumerable: true,
  10004. configurable: true
  10005. });
  10006. Object.defineProperty(Engine, "DECR_WRAP", {
  10007. get: function () {
  10008. return Engine._DECR_WRAP;
  10009. },
  10010. enumerable: true,
  10011. configurable: true
  10012. });
  10013. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10014. get: function () {
  10015. return Engine._ALPHA_DISABLE;
  10016. },
  10017. enumerable: true,
  10018. configurable: true
  10019. });
  10020. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10021. get: function () {
  10022. return Engine._ALPHA_ONEONE;
  10023. },
  10024. enumerable: true,
  10025. configurable: true
  10026. });
  10027. Object.defineProperty(Engine, "ALPHA_ADD", {
  10028. get: function () {
  10029. return Engine._ALPHA_ADD;
  10030. },
  10031. enumerable: true,
  10032. configurable: true
  10033. });
  10034. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10035. get: function () {
  10036. return Engine._ALPHA_COMBINE;
  10037. },
  10038. enumerable: true,
  10039. configurable: true
  10040. });
  10041. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10042. get: function () {
  10043. return Engine._ALPHA_SUBTRACT;
  10044. },
  10045. enumerable: true,
  10046. configurable: true
  10047. });
  10048. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10049. get: function () {
  10050. return Engine._ALPHA_MULTIPLY;
  10051. },
  10052. enumerable: true,
  10053. configurable: true
  10054. });
  10055. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10056. get: function () {
  10057. return Engine._ALPHA_MAXIMIZED;
  10058. },
  10059. enumerable: true,
  10060. configurable: true
  10061. });
  10062. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10063. get: function () {
  10064. return Engine._ALPHA_PREMULTIPLIED;
  10065. },
  10066. enumerable: true,
  10067. configurable: true
  10068. });
  10069. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10070. get: function () {
  10071. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10072. },
  10073. enumerable: true,
  10074. configurable: true
  10075. });
  10076. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10077. get: function () {
  10078. return Engine._ALPHA_INTERPOLATE;
  10079. },
  10080. enumerable: true,
  10081. configurable: true
  10082. });
  10083. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10084. get: function () {
  10085. return Engine._ALPHA_SCREENMODE;
  10086. },
  10087. enumerable: true,
  10088. configurable: true
  10089. });
  10090. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10091. get: function () {
  10092. return Engine._DELAYLOADSTATE_NONE;
  10093. },
  10094. enumerable: true,
  10095. configurable: true
  10096. });
  10097. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10098. get: function () {
  10099. return Engine._DELAYLOADSTATE_LOADED;
  10100. },
  10101. enumerable: true,
  10102. configurable: true
  10103. });
  10104. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10105. get: function () {
  10106. return Engine._DELAYLOADSTATE_LOADING;
  10107. },
  10108. enumerable: true,
  10109. configurable: true
  10110. });
  10111. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10112. get: function () {
  10113. return Engine._DELAYLOADSTATE_NOTLOADED;
  10114. },
  10115. enumerable: true,
  10116. configurable: true
  10117. });
  10118. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10119. get: function () {
  10120. return Engine._TEXTUREFORMAT_ALPHA;
  10121. },
  10122. enumerable: true,
  10123. configurable: true
  10124. });
  10125. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10126. get: function () {
  10127. return Engine._TEXTUREFORMAT_LUMINANCE;
  10128. },
  10129. enumerable: true,
  10130. configurable: true
  10131. });
  10132. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10133. get: function () {
  10134. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10135. },
  10136. enumerable: true,
  10137. configurable: true
  10138. });
  10139. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10140. get: function () {
  10141. return Engine._TEXTUREFORMAT_RGB;
  10142. },
  10143. enumerable: true,
  10144. configurable: true
  10145. });
  10146. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10147. get: function () {
  10148. return Engine._TEXTUREFORMAT_RGBA;
  10149. },
  10150. enumerable: true,
  10151. configurable: true
  10152. });
  10153. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10154. get: function () {
  10155. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10156. },
  10157. enumerable: true,
  10158. configurable: true
  10159. });
  10160. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10161. get: function () {
  10162. return Engine._TEXTURETYPE_FLOAT;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10168. get: function () {
  10169. return Engine._TEXTURETYPE_HALF_FLOAT;
  10170. },
  10171. enumerable: true,
  10172. configurable: true
  10173. });
  10174. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10175. get: function () {
  10176. return Engine._SCALEMODE_FLOOR;
  10177. },
  10178. enumerable: true,
  10179. configurable: true
  10180. });
  10181. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10182. get: function () {
  10183. return Engine._SCALEMODE_NEAREST;
  10184. },
  10185. enumerable: true,
  10186. configurable: true
  10187. });
  10188. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10189. get: function () {
  10190. return Engine._SCALEMODE_CEILING;
  10191. },
  10192. enumerable: true,
  10193. configurable: true
  10194. });
  10195. Object.defineProperty(Engine, "Version", {
  10196. get: function () {
  10197. return "3.2.0-alpha6";
  10198. },
  10199. enumerable: true,
  10200. configurable: true
  10201. });
  10202. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10203. get: function () {
  10204. return this._vrExclusivePointerMode;
  10205. },
  10206. enumerable: true,
  10207. configurable: true
  10208. });
  10209. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10210. get: function () {
  10211. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10212. },
  10213. enumerable: true,
  10214. configurable: true
  10215. });
  10216. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10217. get: function () {
  10218. return this._webGLVersion < 2 || this.forcePOTTextures;
  10219. },
  10220. enumerable: true,
  10221. configurable: true
  10222. });
  10223. Object.defineProperty(Engine.prototype, "badOS", {
  10224. get: function () {
  10225. return this._badOS;
  10226. },
  10227. enumerable: true,
  10228. configurable: true
  10229. });
  10230. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10231. get: function () {
  10232. return this._badDesktopOS;
  10233. },
  10234. enumerable: true,
  10235. configurable: true
  10236. });
  10237. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10238. get: function () {
  10239. return this._performanceMonitor;
  10240. },
  10241. enumerable: true,
  10242. configurable: true
  10243. });
  10244. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10245. get: function () {
  10246. return this._texturesSupported;
  10247. },
  10248. enumerable: true,
  10249. configurable: true
  10250. });
  10251. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10252. get: function () {
  10253. return this._textureFormatInUse;
  10254. },
  10255. enumerable: true,
  10256. configurable: true
  10257. });
  10258. Object.defineProperty(Engine.prototype, "currentViewport", {
  10259. get: function () {
  10260. return this._cachedViewport;
  10261. },
  10262. enumerable: true,
  10263. configurable: true
  10264. });
  10265. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10266. // Empty texture
  10267. get: function () {
  10268. if (!this._emptyTexture) {
  10269. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10270. }
  10271. return this._emptyTexture;
  10272. },
  10273. enumerable: true,
  10274. configurable: true
  10275. });
  10276. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10277. get: function () {
  10278. if (!this._emptyTexture3D) {
  10279. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10280. }
  10281. return this._emptyTexture3D;
  10282. },
  10283. enumerable: true,
  10284. configurable: true
  10285. });
  10286. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10287. get: function () {
  10288. if (!this._emptyCubeTexture) {
  10289. var faceData = new Uint8Array(4);
  10290. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10291. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10292. }
  10293. return this._emptyCubeTexture;
  10294. },
  10295. enumerable: true,
  10296. configurable: true
  10297. });
  10298. Engine.prototype._rebuildInternalTextures = function () {
  10299. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10300. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10301. var internalTexture = currentState_1[_i];
  10302. internalTexture._rebuild();
  10303. }
  10304. };
  10305. Engine.prototype._rebuildEffects = function () {
  10306. for (var key in this._compiledEffects) {
  10307. var effect = this._compiledEffects[key];
  10308. effect._prepareEffect();
  10309. }
  10310. BABYLON.Effect.ResetCache();
  10311. };
  10312. Engine.prototype._rebuildBuffers = function () {
  10313. // Index / Vertex
  10314. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10315. var scene = _a[_i];
  10316. scene.resetCachedMaterial();
  10317. scene._rebuildGeometries();
  10318. scene._rebuildTextures();
  10319. }
  10320. // Uniforms
  10321. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10322. var uniformBuffer = _c[_b];
  10323. uniformBuffer._rebuild();
  10324. }
  10325. };
  10326. Engine.prototype._initGLContext = function () {
  10327. // Caps
  10328. this._caps = new EngineCapabilities();
  10329. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10330. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10331. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10332. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10333. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10334. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10335. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10336. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10337. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10338. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10339. // Infos
  10340. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10341. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10342. if (rendererInfo != null) {
  10343. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10344. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10345. }
  10346. if (!this._glVendor) {
  10347. this._glVendor = "Unknown vendor";
  10348. }
  10349. if (!this._glRenderer) {
  10350. this._glRenderer = "Unknown renderer";
  10351. }
  10352. // Constants
  10353. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10354. if (this._gl.RGBA16F !== 0x881A) {
  10355. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10356. }
  10357. if (this._gl.RGBA32F !== 0x8814) {
  10358. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10359. }
  10360. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10361. this._gl.DEPTH24_STENCIL8 = 35056;
  10362. }
  10363. // Extensions
  10364. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  10365. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  10366. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10367. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10368. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  10369. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  10370. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  10371. 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');
  10372. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  10373. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  10374. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  10375. this._caps.highPrecisionShaderSupported = true;
  10376. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  10377. if (this._caps.timerQuery) {
  10378. if (this._webGLVersion === 1) {
  10379. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  10380. }
  10381. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  10382. }
  10383. // Checks if some of the format renders first to allow the use of webgl inspector.
  10384. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  10385. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  10386. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  10387. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  10388. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  10389. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  10390. if (this._webGLVersion > 1) {
  10391. this._gl.HALF_FLOAT_OES = 0x140B;
  10392. }
  10393. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10394. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10395. // Draw buffers
  10396. if (this._webGLVersion > 1) {
  10397. this._caps.drawBuffersExtension = true;
  10398. }
  10399. else {
  10400. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  10401. if (drawBuffersExtension !== null) {
  10402. this._caps.drawBuffersExtension = true;
  10403. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  10404. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  10405. for (var i = 0; i < 16; i++) {
  10406. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  10407. }
  10408. }
  10409. else {
  10410. this._caps.drawBuffersExtension = false;
  10411. }
  10412. }
  10413. // Depth Texture
  10414. if (this._webGLVersion > 1) {
  10415. this._caps.depthTextureExtension = true;
  10416. }
  10417. else {
  10418. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  10419. if (depthTextureExtension != null) {
  10420. this._caps.depthTextureExtension = true;
  10421. }
  10422. }
  10423. // Vertex array object
  10424. if (this._webGLVersion > 1) {
  10425. this._caps.vertexArrayObject = true;
  10426. }
  10427. else {
  10428. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  10429. if (vertexArrayObjectExtension != null) {
  10430. this._caps.vertexArrayObject = true;
  10431. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  10432. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  10433. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  10434. }
  10435. else {
  10436. this._caps.vertexArrayObject = false;
  10437. }
  10438. }
  10439. // Instances count
  10440. if (this._webGLVersion > 1) {
  10441. this._caps.instancedArrays = true;
  10442. }
  10443. else {
  10444. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  10445. if (instanceExtension != null) {
  10446. this._caps.instancedArrays = true;
  10447. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  10448. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  10449. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  10450. }
  10451. else {
  10452. this._caps.instancedArrays = false;
  10453. }
  10454. }
  10455. // Intelligently add supported compressed formats in order to check for.
  10456. // Check for ASTC support first as it is most powerful and to be very cross platform.
  10457. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  10458. // Likely no hardware which supports both PVR & DXT, so order matters little.
  10459. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  10460. if (this._caps.astc)
  10461. this.texturesSupported.push('-astc.ktx');
  10462. if (this._caps.s3tc)
  10463. this.texturesSupported.push('-dxt.ktx');
  10464. if (this._caps.pvrtc)
  10465. this.texturesSupported.push('-pvrtc.ktx');
  10466. if (this._caps.etc2)
  10467. this.texturesSupported.push('-etc2.ktx');
  10468. if (this._caps.etc1)
  10469. this.texturesSupported.push('-etc1.ktx');
  10470. if (this._gl.getShaderPrecisionFormat) {
  10471. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  10472. if (highp) {
  10473. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  10474. }
  10475. }
  10476. // Depth buffer
  10477. this.setDepthBuffer(true);
  10478. this.setDepthFunctionToLessOrEqual();
  10479. this.setDepthWrite(true);
  10480. // Texture maps
  10481. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  10482. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10483. this._nextFreeTextureSlots.push(slot);
  10484. }
  10485. };
  10486. Object.defineProperty(Engine.prototype, "webGLVersion", {
  10487. get: function () {
  10488. return this._webGLVersion;
  10489. },
  10490. enumerable: true,
  10491. configurable: true
  10492. });
  10493. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  10494. /**
  10495. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  10496. */
  10497. get: function () {
  10498. return this._isStencilEnable;
  10499. },
  10500. enumerable: true,
  10501. configurable: true
  10502. });
  10503. Engine.prototype._prepareWorkingCanvas = function () {
  10504. if (this._workingCanvas) {
  10505. return;
  10506. }
  10507. this._workingCanvas = document.createElement("canvas");
  10508. var context = this._workingCanvas.getContext("2d");
  10509. if (context) {
  10510. this._workingContext = context;
  10511. }
  10512. };
  10513. Engine.prototype.resetTextureCache = function () {
  10514. for (var key in this._boundTexturesCache) {
  10515. var boundTexture = this._boundTexturesCache[key];
  10516. if (boundTexture) {
  10517. this._removeDesignatedSlot(boundTexture);
  10518. }
  10519. this._boundTexturesCache[key] = null;
  10520. }
  10521. if (!this.disableTextureBindingOptimization) {
  10522. this._nextFreeTextureSlots = [];
  10523. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10524. this._nextFreeTextureSlots.push(slot);
  10525. }
  10526. }
  10527. this._currentTextureChannel = -1;
  10528. };
  10529. Engine.prototype.isDeterministicLockStep = function () {
  10530. return this._deterministicLockstep;
  10531. };
  10532. Engine.prototype.getLockstepMaxSteps = function () {
  10533. return this._lockstepMaxSteps;
  10534. };
  10535. Engine.prototype.getGlInfo = function () {
  10536. return {
  10537. vendor: this._glVendor,
  10538. renderer: this._glRenderer,
  10539. version: this._glVersion
  10540. };
  10541. };
  10542. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  10543. if (useScreen === void 0) { useScreen = false; }
  10544. var viewport = camera.viewport;
  10545. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  10546. };
  10547. Engine.prototype.getRenderWidth = function (useScreen) {
  10548. if (useScreen === void 0) { useScreen = false; }
  10549. if (!useScreen && this._currentRenderTarget) {
  10550. return this._currentRenderTarget.width;
  10551. }
  10552. return this._gl.drawingBufferWidth;
  10553. };
  10554. Engine.prototype.getRenderHeight = function (useScreen) {
  10555. if (useScreen === void 0) { useScreen = false; }
  10556. if (!useScreen && this._currentRenderTarget) {
  10557. return this._currentRenderTarget.height;
  10558. }
  10559. return this._gl.drawingBufferHeight;
  10560. };
  10561. Engine.prototype.getRenderingCanvas = function () {
  10562. return this._renderingCanvas;
  10563. };
  10564. Engine.prototype.getRenderingCanvasClientRect = function () {
  10565. if (!this._renderingCanvas) {
  10566. return null;
  10567. }
  10568. return this._renderingCanvas.getBoundingClientRect();
  10569. };
  10570. Engine.prototype.setHardwareScalingLevel = function (level) {
  10571. this._hardwareScalingLevel = level;
  10572. this.resize();
  10573. };
  10574. Engine.prototype.getHardwareScalingLevel = function () {
  10575. return this._hardwareScalingLevel;
  10576. };
  10577. Engine.prototype.getLoadedTexturesCache = function () {
  10578. return this._internalTexturesCache;
  10579. };
  10580. Engine.prototype.getCaps = function () {
  10581. return this._caps;
  10582. };
  10583. Object.defineProperty(Engine.prototype, "drawCalls", {
  10584. /** The number of draw calls submitted last frame */
  10585. get: function () {
  10586. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10587. return 0;
  10588. },
  10589. enumerable: true,
  10590. configurable: true
  10591. });
  10592. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10593. get: function () {
  10594. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10595. return null;
  10596. },
  10597. enumerable: true,
  10598. configurable: true
  10599. });
  10600. Engine.prototype.getDepthFunction = function () {
  10601. return this._depthCullingState.depthFunc;
  10602. };
  10603. Engine.prototype.setDepthFunction = function (depthFunc) {
  10604. this._depthCullingState.depthFunc = depthFunc;
  10605. };
  10606. Engine.prototype.setDepthFunctionToGreater = function () {
  10607. this._depthCullingState.depthFunc = this._gl.GREATER;
  10608. };
  10609. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10610. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10611. };
  10612. Engine.prototype.setDepthFunctionToLess = function () {
  10613. this._depthCullingState.depthFunc = this._gl.LESS;
  10614. };
  10615. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10616. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10617. };
  10618. Engine.prototype.getStencilBuffer = function () {
  10619. return this._stencilState.stencilTest;
  10620. };
  10621. Engine.prototype.setStencilBuffer = function (enable) {
  10622. this._stencilState.stencilTest = enable;
  10623. };
  10624. Engine.prototype.getStencilMask = function () {
  10625. return this._stencilState.stencilMask;
  10626. };
  10627. Engine.prototype.setStencilMask = function (mask) {
  10628. this._stencilState.stencilMask = mask;
  10629. };
  10630. Engine.prototype.getStencilFunction = function () {
  10631. return this._stencilState.stencilFunc;
  10632. };
  10633. Engine.prototype.getStencilFunctionReference = function () {
  10634. return this._stencilState.stencilFuncRef;
  10635. };
  10636. Engine.prototype.getStencilFunctionMask = function () {
  10637. return this._stencilState.stencilFuncMask;
  10638. };
  10639. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10640. this._stencilState.stencilFunc = stencilFunc;
  10641. };
  10642. Engine.prototype.setStencilFunctionReference = function (reference) {
  10643. this._stencilState.stencilFuncRef = reference;
  10644. };
  10645. Engine.prototype.setStencilFunctionMask = function (mask) {
  10646. this._stencilState.stencilFuncMask = mask;
  10647. };
  10648. Engine.prototype.getStencilOperationFail = function () {
  10649. return this._stencilState.stencilOpStencilFail;
  10650. };
  10651. Engine.prototype.getStencilOperationDepthFail = function () {
  10652. return this._stencilState.stencilOpDepthFail;
  10653. };
  10654. Engine.prototype.getStencilOperationPass = function () {
  10655. return this._stencilState.stencilOpStencilDepthPass;
  10656. };
  10657. Engine.prototype.setStencilOperationFail = function (operation) {
  10658. this._stencilState.stencilOpStencilFail = operation;
  10659. };
  10660. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10661. this._stencilState.stencilOpDepthFail = operation;
  10662. };
  10663. Engine.prototype.setStencilOperationPass = function (operation) {
  10664. this._stencilState.stencilOpStencilDepthPass = operation;
  10665. };
  10666. Engine.prototype.setDitheringState = function (value) {
  10667. if (value) {
  10668. this._gl.enable(this._gl.DITHER);
  10669. }
  10670. else {
  10671. this._gl.disable(this._gl.DITHER);
  10672. }
  10673. };
  10674. Engine.prototype.setRasterizerState = function (value) {
  10675. if (value) {
  10676. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10677. }
  10678. else {
  10679. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10680. }
  10681. };
  10682. /**
  10683. * stop executing a render loop function and remove it from the execution array
  10684. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10685. */
  10686. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10687. if (!renderFunction) {
  10688. this._activeRenderLoops = [];
  10689. return;
  10690. }
  10691. var index = this._activeRenderLoops.indexOf(renderFunction);
  10692. if (index >= 0) {
  10693. this._activeRenderLoops.splice(index, 1);
  10694. }
  10695. };
  10696. Engine.prototype._renderLoop = function () {
  10697. if (!this._contextWasLost) {
  10698. var shouldRender = true;
  10699. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10700. shouldRender = false;
  10701. }
  10702. if (shouldRender) {
  10703. // Start new frame
  10704. this.beginFrame();
  10705. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10706. var renderFunction = this._activeRenderLoops[index];
  10707. renderFunction();
  10708. }
  10709. // Present
  10710. this.endFrame();
  10711. }
  10712. }
  10713. if (this._activeRenderLoops.length > 0) {
  10714. // Register new frame
  10715. var requester = null;
  10716. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10717. requester = this._vrDisplay;
  10718. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10719. }
  10720. else {
  10721. this._renderingQueueLaunched = false;
  10722. }
  10723. };
  10724. /**
  10725. * Register and execute a render loop. The engine can have more than one render function.
  10726. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10727. * @example
  10728. * engine.runRenderLoop(function () {
  10729. * scene.render()
  10730. * })
  10731. */
  10732. Engine.prototype.runRenderLoop = function (renderFunction) {
  10733. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10734. return;
  10735. }
  10736. this._activeRenderLoops.push(renderFunction);
  10737. if (!this._renderingQueueLaunched) {
  10738. this._renderingQueueLaunched = true;
  10739. this._bindedRenderFunction = this._renderLoop.bind(this);
  10740. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10741. }
  10742. };
  10743. /**
  10744. * Toggle full screen mode.
  10745. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10746. * @param {any} options - an options object to be sent to the requestFullscreen function
  10747. */
  10748. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10749. if (this.isFullscreen) {
  10750. BABYLON.Tools.ExitFullscreen();
  10751. }
  10752. else {
  10753. this._pointerLockRequested = requestPointerLock;
  10754. if (this._renderingCanvas) {
  10755. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10756. }
  10757. }
  10758. };
  10759. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10760. if (stencil === void 0) { stencil = false; }
  10761. this.applyStates();
  10762. var mode = 0;
  10763. if (backBuffer && color) {
  10764. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10765. mode |= this._gl.COLOR_BUFFER_BIT;
  10766. }
  10767. if (depth) {
  10768. this._gl.clearDepth(1.0);
  10769. mode |= this._gl.DEPTH_BUFFER_BIT;
  10770. }
  10771. if (stencil) {
  10772. this._gl.clearStencil(0);
  10773. mode |= this._gl.STENCIL_BUFFER_BIT;
  10774. }
  10775. this._gl.clear(mode);
  10776. };
  10777. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10778. var gl = this._gl;
  10779. // Save state
  10780. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10781. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10782. // Change state
  10783. gl.enable(gl.SCISSOR_TEST);
  10784. gl.scissor(x, y, width, height);
  10785. // Clear
  10786. this.clear(clearColor, true, true, true);
  10787. // Restore state
  10788. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10789. if (curScissor === true) {
  10790. gl.enable(gl.SCISSOR_TEST);
  10791. }
  10792. else {
  10793. gl.disable(gl.SCISSOR_TEST);
  10794. }
  10795. };
  10796. /**
  10797. * Set the WebGL's viewport
  10798. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10799. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10800. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10801. */
  10802. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10803. var width = requiredWidth || this.getRenderWidth();
  10804. var height = requiredHeight || this.getRenderHeight();
  10805. var x = viewport.x || 0;
  10806. var y = viewport.y || 0;
  10807. this._cachedViewport = viewport;
  10808. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10809. };
  10810. /**
  10811. * Directly set the WebGL Viewport
  10812. * The x, y, width & height are directly passed to the WebGL call
  10813. * @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.
  10814. */
  10815. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10816. var currentViewport = this._cachedViewport;
  10817. this._cachedViewport = null;
  10818. this._gl.viewport(x, y, width, height);
  10819. return currentViewport;
  10820. };
  10821. Engine.prototype.beginFrame = function () {
  10822. this.onBeginFrameObservable.notifyObservers(this);
  10823. this._measureFps();
  10824. };
  10825. Engine.prototype.endFrame = function () {
  10826. //force a flush in case we are using a bad OS.
  10827. if (this._badOS) {
  10828. this.flushFramebuffer();
  10829. }
  10830. //submit frame to the vr device, if enabled
  10831. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10832. // TODO: We should only submit the frame if we read frameData successfully.
  10833. this._vrDisplay.submitFrame();
  10834. }
  10835. this.onEndFrameObservable.notifyObservers(this);
  10836. };
  10837. /**
  10838. * resize the view according to the canvas' size.
  10839. * @example
  10840. * window.addEventListener("resize", function () {
  10841. * engine.resize();
  10842. * });
  10843. */
  10844. Engine.prototype.resize = function () {
  10845. // We're not resizing the size of the canvas while in VR mode & presenting
  10846. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10847. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10848. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10849. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10850. }
  10851. };
  10852. /**
  10853. * force a specific size of the canvas
  10854. * @param {number} width - the new canvas' width
  10855. * @param {number} height - the new canvas' height
  10856. */
  10857. Engine.prototype.setSize = function (width, height) {
  10858. if (!this._renderingCanvas) {
  10859. return;
  10860. }
  10861. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10862. return;
  10863. }
  10864. this._renderingCanvas.width = width;
  10865. this._renderingCanvas.height = height;
  10866. for (var index = 0; index < this.scenes.length; index++) {
  10867. var scene = this.scenes[index];
  10868. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10869. var cam = scene.cameras[camIndex];
  10870. cam._currentRenderId = 0;
  10871. }
  10872. }
  10873. if (this.onResizeObservable.hasObservers) {
  10874. this.onResizeObservable.notifyObservers(this);
  10875. }
  10876. };
  10877. // WebVR functions
  10878. Engine.prototype.isVRDevicePresent = function () {
  10879. return !!this._vrDisplay;
  10880. };
  10881. Engine.prototype.getVRDevice = function () {
  10882. return this._vrDisplay;
  10883. };
  10884. Engine.prototype.initWebVR = function () {
  10885. var _this = this;
  10886. var notifyObservers = function () {
  10887. var eventArgs = {
  10888. vrDisplay: _this._vrDisplay,
  10889. vrSupported: _this._vrSupported
  10890. };
  10891. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10892. };
  10893. if (!this._onVrDisplayConnect) {
  10894. this._onVrDisplayConnect = function (event) {
  10895. _this._vrDisplay = event.display;
  10896. notifyObservers();
  10897. };
  10898. this._onVrDisplayDisconnect = function () {
  10899. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10900. _this._vrDisplay = undefined;
  10901. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10902. notifyObservers();
  10903. };
  10904. this._onVrDisplayPresentChange = function () {
  10905. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10906. };
  10907. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10908. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10909. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10910. }
  10911. this._getVRDisplays(notifyObservers);
  10912. return this.onVRDisplayChangedObservable;
  10913. };
  10914. Engine.prototype.enableVR = function () {
  10915. var _this = this;
  10916. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10917. var onResolved = function () {
  10918. _this.onVRRequestPresentComplete.notifyObservers(true);
  10919. _this._onVRFullScreenTriggered();
  10920. };
  10921. var onRejected = function () {
  10922. _this.onVRRequestPresentComplete.notifyObservers(false);
  10923. };
  10924. this.onVRRequestPresentStart.notifyObservers(this);
  10925. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10926. }
  10927. };
  10928. Engine.prototype.disableVR = function () {
  10929. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10930. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10931. }
  10932. };
  10933. Engine.prototype._getVRDisplays = function (callback) {
  10934. var _this = this;
  10935. var getWebVRDevices = function (devices) {
  10936. _this._vrSupported = true;
  10937. // note that devices may actually be an empty array. This is fine;
  10938. // we expect this._vrDisplay to be undefined in this case.
  10939. return _this._vrDisplay = devices[0];
  10940. };
  10941. if (navigator.getVRDisplays) {
  10942. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10943. // TODO: System CANNOT support WebVR, despite API presence.
  10944. _this._vrSupported = false;
  10945. callback();
  10946. });
  10947. }
  10948. else {
  10949. // TODO: Browser does not support WebVR
  10950. this._vrDisplay = undefined;
  10951. this._vrSupported = false;
  10952. callback();
  10953. }
  10954. };
  10955. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10956. if (this._currentRenderTarget) {
  10957. this.unBindFramebuffer(this._currentRenderTarget);
  10958. }
  10959. this._currentRenderTarget = texture;
  10960. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10961. var gl = this._gl;
  10962. if (texture.isCube) {
  10963. if (faceIndex === undefined) {
  10964. faceIndex = 0;
  10965. }
  10966. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10967. }
  10968. if (this._cachedViewport && !forceFullscreenViewport) {
  10969. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10970. }
  10971. else {
  10972. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10973. }
  10974. this.wipeCaches();
  10975. };
  10976. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10977. if (this._currentFramebuffer !== framebuffer) {
  10978. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10979. this._currentFramebuffer = framebuffer;
  10980. }
  10981. };
  10982. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10983. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10984. this._currentRenderTarget = null;
  10985. // If MSAA, we need to bitblt back to main texture
  10986. var gl = this._gl;
  10987. if (texture._MSAAFramebuffer) {
  10988. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10989. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10990. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10991. }
  10992. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10993. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10994. gl.generateMipmap(gl.TEXTURE_2D);
  10995. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10996. }
  10997. if (onBeforeUnbind) {
  10998. if (texture._MSAAFramebuffer) {
  10999. // Bind the correct framebuffer
  11000. this.bindUnboundFramebuffer(texture._framebuffer);
  11001. }
  11002. onBeforeUnbind();
  11003. }
  11004. this.bindUnboundFramebuffer(null);
  11005. };
  11006. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11007. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11008. this._currentRenderTarget = null;
  11009. // If MSAA, we need to bitblt back to main texture
  11010. var gl = this._gl;
  11011. if (textures[0]._MSAAFramebuffer) {
  11012. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11013. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11014. var attachments = textures[0]._attachments;
  11015. if (!attachments) {
  11016. attachments = new Array(textures.length);
  11017. textures[0]._attachments = attachments;
  11018. }
  11019. for (var i = 0; i < textures.length; i++) {
  11020. var texture = textures[i];
  11021. for (var j = 0; j < attachments.length; j++) {
  11022. attachments[j] = gl.NONE;
  11023. }
  11024. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11025. gl.readBuffer(attachments[i]);
  11026. gl.drawBuffers(attachments);
  11027. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11028. }
  11029. for (var i = 0; i < attachments.length; i++) {
  11030. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11031. }
  11032. gl.drawBuffers(attachments);
  11033. }
  11034. for (var i = 0; i < textures.length; i++) {
  11035. var texture = textures[i];
  11036. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11037. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11038. gl.generateMipmap(gl.TEXTURE_2D);
  11039. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11040. }
  11041. }
  11042. if (onBeforeUnbind) {
  11043. if (textures[0]._MSAAFramebuffer) {
  11044. // Bind the correct framebuffer
  11045. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11046. }
  11047. onBeforeUnbind();
  11048. }
  11049. this.bindUnboundFramebuffer(null);
  11050. };
  11051. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11052. if (texture.generateMipMaps) {
  11053. var gl = this._gl;
  11054. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11055. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11056. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11057. }
  11058. };
  11059. Engine.prototype.flushFramebuffer = function () {
  11060. this._gl.flush();
  11061. };
  11062. Engine.prototype.restoreDefaultFramebuffer = function () {
  11063. if (this._currentRenderTarget) {
  11064. this.unBindFramebuffer(this._currentRenderTarget);
  11065. }
  11066. else {
  11067. this.bindUnboundFramebuffer(null);
  11068. }
  11069. if (this._cachedViewport) {
  11070. this.setViewport(this._cachedViewport);
  11071. }
  11072. this.wipeCaches();
  11073. };
  11074. // UBOs
  11075. Engine.prototype.createUniformBuffer = function (elements) {
  11076. var ubo = this._gl.createBuffer();
  11077. if (!ubo) {
  11078. throw new Error("Unable to create uniform buffer");
  11079. }
  11080. this.bindUniformBuffer(ubo);
  11081. if (elements instanceof Float32Array) {
  11082. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11083. }
  11084. else {
  11085. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11086. }
  11087. this.bindUniformBuffer(null);
  11088. ubo.references = 1;
  11089. return ubo;
  11090. };
  11091. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11092. var ubo = this._gl.createBuffer();
  11093. if (!ubo) {
  11094. throw new Error("Unable to create dynamic uniform buffer");
  11095. }
  11096. this.bindUniformBuffer(ubo);
  11097. if (elements instanceof Float32Array) {
  11098. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11099. }
  11100. else {
  11101. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11102. }
  11103. this.bindUniformBuffer(null);
  11104. ubo.references = 1;
  11105. return ubo;
  11106. };
  11107. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11108. this.bindUniformBuffer(uniformBuffer);
  11109. if (offset === undefined) {
  11110. offset = 0;
  11111. }
  11112. if (count === undefined) {
  11113. if (elements instanceof Float32Array) {
  11114. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11115. }
  11116. else {
  11117. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11118. }
  11119. }
  11120. else {
  11121. if (elements instanceof Float32Array) {
  11122. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11123. }
  11124. else {
  11125. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11126. }
  11127. }
  11128. this.bindUniformBuffer(null);
  11129. };
  11130. // VBOs
  11131. Engine.prototype._resetVertexBufferBinding = function () {
  11132. this.bindArrayBuffer(null);
  11133. this._cachedVertexBuffers = null;
  11134. };
  11135. Engine.prototype.createVertexBuffer = function (vertices) {
  11136. var vbo = this._gl.createBuffer();
  11137. if (!vbo) {
  11138. throw new Error("Unable to create vertex buffer");
  11139. }
  11140. this.bindArrayBuffer(vbo);
  11141. if (vertices instanceof Float32Array) {
  11142. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11143. }
  11144. else {
  11145. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11146. }
  11147. this._resetVertexBufferBinding();
  11148. vbo.references = 1;
  11149. return vbo;
  11150. };
  11151. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11152. var vbo = this._gl.createBuffer();
  11153. if (!vbo) {
  11154. throw new Error("Unable to create dynamic vertex buffer");
  11155. }
  11156. this.bindArrayBuffer(vbo);
  11157. if (vertices instanceof Float32Array) {
  11158. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11159. }
  11160. else {
  11161. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11162. }
  11163. this._resetVertexBufferBinding();
  11164. vbo.references = 1;
  11165. return vbo;
  11166. };
  11167. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11168. if (offset === void 0) { offset = 0; }
  11169. // Force cache update
  11170. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11171. this.bindIndexBuffer(indexBuffer);
  11172. var arrayBuffer;
  11173. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11174. arrayBuffer = indices;
  11175. }
  11176. else {
  11177. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11178. }
  11179. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11180. this._resetIndexBufferBinding();
  11181. };
  11182. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11183. this.bindArrayBuffer(vertexBuffer);
  11184. if (offset === undefined) {
  11185. offset = 0;
  11186. }
  11187. if (count === undefined) {
  11188. if (vertices instanceof Float32Array) {
  11189. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11190. }
  11191. else {
  11192. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11193. }
  11194. }
  11195. else {
  11196. if (vertices instanceof Float32Array) {
  11197. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11198. }
  11199. else {
  11200. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11201. }
  11202. }
  11203. this._resetVertexBufferBinding();
  11204. };
  11205. Engine.prototype._resetIndexBufferBinding = function () {
  11206. this.bindIndexBuffer(null);
  11207. this._cachedIndexBuffer = null;
  11208. };
  11209. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11210. var vbo = this._gl.createBuffer();
  11211. if (!vbo) {
  11212. throw new Error("Unable to create index buffer");
  11213. }
  11214. this.bindIndexBuffer(vbo);
  11215. // Check for 32 bits indices
  11216. var arrayBuffer;
  11217. var need32Bits = false;
  11218. if (indices instanceof Uint16Array) {
  11219. arrayBuffer = indices;
  11220. }
  11221. else {
  11222. //check 32 bit support
  11223. if (this._caps.uintIndices) {
  11224. if (indices instanceof Uint32Array) {
  11225. arrayBuffer = indices;
  11226. need32Bits = true;
  11227. }
  11228. else {
  11229. //number[] or Int32Array, check if 32 bit is necessary
  11230. for (var index = 0; index < indices.length; index++) {
  11231. if (indices[index] > 65535) {
  11232. need32Bits = true;
  11233. break;
  11234. }
  11235. }
  11236. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11237. }
  11238. }
  11239. else {
  11240. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11241. arrayBuffer = new Uint16Array(indices);
  11242. }
  11243. }
  11244. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11245. this._resetIndexBufferBinding();
  11246. vbo.references = 1;
  11247. vbo.is32Bits = need32Bits;
  11248. return vbo;
  11249. };
  11250. Engine.prototype.bindArrayBuffer = function (buffer) {
  11251. if (!this._vaoRecordInProgress) {
  11252. this._unbindVertexArrayObject();
  11253. }
  11254. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11255. };
  11256. Engine.prototype.bindUniformBuffer = function (buffer) {
  11257. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11258. };
  11259. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11260. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11261. };
  11262. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11263. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11264. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11265. };
  11266. ;
  11267. Engine.prototype.bindIndexBuffer = function (buffer) {
  11268. if (!this._vaoRecordInProgress) {
  11269. this._unbindVertexArrayObject();
  11270. }
  11271. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11272. };
  11273. Engine.prototype.bindBuffer = function (buffer, target) {
  11274. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11275. this._gl.bindBuffer(target, buffer);
  11276. this._currentBoundBuffer[target] = buffer;
  11277. }
  11278. };
  11279. Engine.prototype.updateArrayBuffer = function (data) {
  11280. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11281. };
  11282. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11283. var pointer = this._currentBufferPointers[indx];
  11284. var changed = false;
  11285. if (!pointer.active) {
  11286. changed = true;
  11287. pointer.active = true;
  11288. pointer.index = indx;
  11289. pointer.size = size;
  11290. pointer.type = type;
  11291. pointer.normalized = normalized;
  11292. pointer.stride = stride;
  11293. pointer.offset = offset;
  11294. pointer.buffer = buffer;
  11295. }
  11296. else {
  11297. if (pointer.buffer !== buffer) {
  11298. pointer.buffer = buffer;
  11299. changed = true;
  11300. }
  11301. if (pointer.size !== size) {
  11302. pointer.size = size;
  11303. changed = true;
  11304. }
  11305. if (pointer.type !== type) {
  11306. pointer.type = type;
  11307. changed = true;
  11308. }
  11309. if (pointer.normalized !== normalized) {
  11310. pointer.normalized = normalized;
  11311. changed = true;
  11312. }
  11313. if (pointer.stride !== stride) {
  11314. pointer.stride = stride;
  11315. changed = true;
  11316. }
  11317. if (pointer.offset !== offset) {
  11318. pointer.offset = offset;
  11319. changed = true;
  11320. }
  11321. }
  11322. if (changed || this._vaoRecordInProgress) {
  11323. this.bindArrayBuffer(buffer);
  11324. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11325. }
  11326. };
  11327. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11328. if (indexBuffer == null) {
  11329. return;
  11330. }
  11331. if (this._cachedIndexBuffer !== indexBuffer) {
  11332. this._cachedIndexBuffer = indexBuffer;
  11333. this.bindIndexBuffer(indexBuffer);
  11334. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11335. }
  11336. };
  11337. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11338. var attributes = effect.getAttributesNames();
  11339. if (!this._vaoRecordInProgress) {
  11340. this._unbindVertexArrayObject();
  11341. }
  11342. this.unbindAllAttributes();
  11343. for (var index = 0; index < attributes.length; index++) {
  11344. var order = effect.getAttributeLocation(index);
  11345. if (order >= 0) {
  11346. var vertexBuffer = vertexBuffers[attributes[index]];
  11347. if (!vertexBuffer) {
  11348. continue;
  11349. }
  11350. this._gl.enableVertexAttribArray(order);
  11351. if (!this._vaoRecordInProgress) {
  11352. this._vertexAttribArraysEnabled[order] = true;
  11353. }
  11354. var buffer = vertexBuffer.getBuffer();
  11355. if (buffer) {
  11356. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11357. if (vertexBuffer.getIsInstanced()) {
  11358. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11359. if (!this._vaoRecordInProgress) {
  11360. this._currentInstanceLocations.push(order);
  11361. this._currentInstanceBuffers.push(buffer);
  11362. }
  11363. }
  11364. }
  11365. }
  11366. }
  11367. };
  11368. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  11369. var vao = this._gl.createVertexArray();
  11370. this._vaoRecordInProgress = true;
  11371. this._gl.bindVertexArray(vao);
  11372. this._mustWipeVertexAttributes = true;
  11373. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11374. this.bindIndexBuffer(indexBuffer);
  11375. this._vaoRecordInProgress = false;
  11376. this._gl.bindVertexArray(null);
  11377. return vao;
  11378. };
  11379. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  11380. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  11381. this._cachedVertexArrayObject = vertexArrayObject;
  11382. this._gl.bindVertexArray(vertexArrayObject);
  11383. this._cachedVertexBuffers = null;
  11384. this._cachedIndexBuffer = null;
  11385. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  11386. this._mustWipeVertexAttributes = true;
  11387. }
  11388. };
  11389. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  11390. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  11391. this._cachedVertexBuffers = vertexBuffer;
  11392. this._cachedEffectForVertexBuffers = effect;
  11393. var attributesCount = effect.getAttributesCount();
  11394. this._unbindVertexArrayObject();
  11395. this.unbindAllAttributes();
  11396. var offset = 0;
  11397. for (var index = 0; index < attributesCount; index++) {
  11398. if (index < vertexDeclaration.length) {
  11399. var order = effect.getAttributeLocation(index);
  11400. if (order >= 0) {
  11401. this._gl.enableVertexAttribArray(order);
  11402. this._vertexAttribArraysEnabled[order] = true;
  11403. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  11404. }
  11405. offset += vertexDeclaration[index] * 4;
  11406. }
  11407. }
  11408. }
  11409. this._bindIndexBufferWithCache(indexBuffer);
  11410. };
  11411. Engine.prototype._unbindVertexArrayObject = function () {
  11412. if (!this._cachedVertexArrayObject) {
  11413. return;
  11414. }
  11415. this._cachedVertexArrayObject = null;
  11416. this._gl.bindVertexArray(null);
  11417. };
  11418. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  11419. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  11420. this._cachedVertexBuffers = vertexBuffers;
  11421. this._cachedEffectForVertexBuffers = effect;
  11422. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11423. }
  11424. this._bindIndexBufferWithCache(indexBuffer);
  11425. };
  11426. Engine.prototype.unbindInstanceAttributes = function () {
  11427. var boundBuffer;
  11428. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  11429. var instancesBuffer = this._currentInstanceBuffers[i];
  11430. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  11431. boundBuffer = instancesBuffer;
  11432. this.bindArrayBuffer(instancesBuffer);
  11433. }
  11434. var offsetLocation = this._currentInstanceLocations[i];
  11435. this._gl.vertexAttribDivisor(offsetLocation, 0);
  11436. }
  11437. this._currentInstanceBuffers.length = 0;
  11438. this._currentInstanceLocations.length = 0;
  11439. };
  11440. Engine.prototype.releaseVertexArrayObject = function (vao) {
  11441. this._gl.deleteVertexArray(vao);
  11442. };
  11443. Engine.prototype._releaseBuffer = function (buffer) {
  11444. buffer.references--;
  11445. if (buffer.references === 0) {
  11446. this._gl.deleteBuffer(buffer);
  11447. return true;
  11448. }
  11449. return false;
  11450. };
  11451. Engine.prototype.createInstancesBuffer = function (capacity) {
  11452. var buffer = this._gl.createBuffer();
  11453. if (!buffer) {
  11454. throw new Error("Unable to create instance buffer");
  11455. }
  11456. buffer.capacity = capacity;
  11457. this.bindArrayBuffer(buffer);
  11458. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  11459. return buffer;
  11460. };
  11461. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  11462. this._gl.deleteBuffer(buffer);
  11463. };
  11464. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  11465. this.bindArrayBuffer(instancesBuffer);
  11466. if (data) {
  11467. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11468. }
  11469. if (offsetLocations[0].index !== undefined) {
  11470. var stride = 0;
  11471. for (var i = 0; i < offsetLocations.length; i++) {
  11472. var ai = offsetLocations[i];
  11473. stride += ai.attributeSize * 4;
  11474. }
  11475. for (var i = 0; i < offsetLocations.length; i++) {
  11476. var ai = offsetLocations[i];
  11477. if (!this._vertexAttribArraysEnabled[ai.index]) {
  11478. this._gl.enableVertexAttribArray(ai.index);
  11479. this._vertexAttribArraysEnabled[ai.index] = true;
  11480. }
  11481. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  11482. this._gl.vertexAttribDivisor(ai.index, 1);
  11483. this._currentInstanceLocations.push(ai.index);
  11484. this._currentInstanceBuffers.push(instancesBuffer);
  11485. }
  11486. }
  11487. else {
  11488. for (var index = 0; index < 4; index++) {
  11489. var offsetLocation = offsetLocations[index];
  11490. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  11491. this._gl.enableVertexAttribArray(offsetLocation);
  11492. this._vertexAttribArraysEnabled[offsetLocation] = true;
  11493. }
  11494. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  11495. this._gl.vertexAttribDivisor(offsetLocation, 1);
  11496. this._currentInstanceLocations.push(offsetLocation);
  11497. this._currentInstanceBuffers.push(instancesBuffer);
  11498. }
  11499. }
  11500. };
  11501. Engine.prototype.applyStates = function () {
  11502. this._depthCullingState.apply(this._gl);
  11503. this._stencilState.apply(this._gl);
  11504. this._alphaState.apply(this._gl);
  11505. };
  11506. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  11507. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  11508. };
  11509. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  11510. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  11511. };
  11512. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  11513. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  11514. };
  11515. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  11516. // Apply states
  11517. this.applyStates();
  11518. this._drawCalls.addCount(1, false);
  11519. // Render
  11520. var drawMode = this.DrawMode(fillMode);
  11521. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  11522. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  11523. if (instancesCount) {
  11524. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  11525. }
  11526. else {
  11527. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  11528. }
  11529. };
  11530. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  11531. // Apply states
  11532. this.applyStates();
  11533. this._drawCalls.addCount(1, false);
  11534. var drawMode = this.DrawMode(fillMode);
  11535. if (instancesCount) {
  11536. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  11537. }
  11538. else {
  11539. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  11540. }
  11541. };
  11542. Engine.prototype.DrawMode = function (fillMode) {
  11543. switch (fillMode) {
  11544. // Triangle views
  11545. case BABYLON.Material.TriangleFillMode:
  11546. return this._gl.TRIANGLES;
  11547. case BABYLON.Material.PointFillMode:
  11548. return this._gl.POINTS;
  11549. case BABYLON.Material.WireFrameFillMode:
  11550. return this._gl.LINES;
  11551. // Draw modes
  11552. case BABYLON.Material.PointListDrawMode:
  11553. return this._gl.POINTS;
  11554. case BABYLON.Material.LineListDrawMode:
  11555. return this._gl.LINES;
  11556. case BABYLON.Material.LineLoopDrawMode:
  11557. return this._gl.LINE_LOOP;
  11558. case BABYLON.Material.LineStripDrawMode:
  11559. return this._gl.LINE_STRIP;
  11560. case BABYLON.Material.TriangleStripDrawMode:
  11561. return this._gl.TRIANGLE_STRIP;
  11562. case BABYLON.Material.TriangleFanDrawMode:
  11563. return this._gl.TRIANGLE_FAN;
  11564. default:
  11565. return this._gl.TRIANGLES;
  11566. }
  11567. };
  11568. // Shaders
  11569. Engine.prototype._releaseEffect = function (effect) {
  11570. if (this._compiledEffects[effect._key]) {
  11571. delete this._compiledEffects[effect._key];
  11572. this._deleteProgram(effect.getProgram());
  11573. }
  11574. };
  11575. Engine.prototype._deleteProgram = function (program) {
  11576. if (program) {
  11577. program.__SPECTOR_rebuildProgram = null;
  11578. if (program.transformFeedback) {
  11579. this.deleteTransformFeedback(program.transformFeedback);
  11580. program.transformFeedback = null;
  11581. }
  11582. this._gl.deleteProgram(program);
  11583. }
  11584. };
  11585. /**
  11586. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11587. * @param samplers An array of string used to represent textures
  11588. */
  11589. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11590. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11591. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11592. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11593. if (this._compiledEffects[name]) {
  11594. var compiledEffect = this._compiledEffects[name];
  11595. if (onCompiled && compiledEffect.isReady()) {
  11596. onCompiled(compiledEffect);
  11597. }
  11598. return compiledEffect;
  11599. }
  11600. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11601. effect._key = name;
  11602. this._compiledEffects[name] = effect;
  11603. return effect;
  11604. };
  11605. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11606. if (uniformsNames === void 0) { uniformsNames = []; }
  11607. if (samplers === void 0) { samplers = []; }
  11608. if (defines === void 0) { defines = ""; }
  11609. return this.createEffect({
  11610. vertex: "particles",
  11611. fragmentElement: fragmentName
  11612. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11613. };
  11614. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11615. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11616. context = context || this._gl;
  11617. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11618. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11619. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11620. };
  11621. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11622. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11623. context = context || this._gl;
  11624. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11625. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11626. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11627. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11628. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11629. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11630. return program;
  11631. };
  11632. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11633. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11634. var shaderProgram = context.createProgram();
  11635. if (!shaderProgram) {
  11636. throw new Error("Unable to create program");
  11637. }
  11638. context.attachShader(shaderProgram, vertexShader);
  11639. context.attachShader(shaderProgram, fragmentShader);
  11640. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11641. var transformFeedback = this.createTransformFeedback();
  11642. this.bindTransformFeedback(transformFeedback);
  11643. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11644. shaderProgram.transformFeedback = transformFeedback;
  11645. }
  11646. context.linkProgram(shaderProgram);
  11647. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11648. this.bindTransformFeedback(null);
  11649. }
  11650. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11651. if (!linked) {
  11652. context.validateProgram(shaderProgram);
  11653. var error = context.getProgramInfoLog(shaderProgram);
  11654. if (error) {
  11655. throw new Error(error);
  11656. }
  11657. }
  11658. context.deleteShader(vertexShader);
  11659. context.deleteShader(fragmentShader);
  11660. return shaderProgram;
  11661. };
  11662. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11663. var results = new Array();
  11664. for (var index = 0; index < uniformsNames.length; index++) {
  11665. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11666. }
  11667. return results;
  11668. };
  11669. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11670. var results = [];
  11671. for (var index = 0; index < attributesNames.length; index++) {
  11672. try {
  11673. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11674. }
  11675. catch (e) {
  11676. results.push(-1);
  11677. }
  11678. }
  11679. return results;
  11680. };
  11681. Engine.prototype.enableEffect = function (effect) {
  11682. if (!effect) {
  11683. return;
  11684. }
  11685. // Use program
  11686. this.bindSamplers(effect);
  11687. this._currentEffect = effect;
  11688. if (effect.onBind) {
  11689. effect.onBind(effect);
  11690. }
  11691. effect.onBindObservable.notifyObservers(effect);
  11692. };
  11693. Engine.prototype.setIntArray = function (uniform, array) {
  11694. if (!uniform)
  11695. return;
  11696. this._gl.uniform1iv(uniform, array);
  11697. };
  11698. Engine.prototype.setIntArray2 = function (uniform, array) {
  11699. if (!uniform || array.length % 2 !== 0)
  11700. return;
  11701. this._gl.uniform2iv(uniform, array);
  11702. };
  11703. Engine.prototype.setIntArray3 = function (uniform, array) {
  11704. if (!uniform || array.length % 3 !== 0)
  11705. return;
  11706. this._gl.uniform3iv(uniform, array);
  11707. };
  11708. Engine.prototype.setIntArray4 = function (uniform, array) {
  11709. if (!uniform || array.length % 4 !== 0)
  11710. return;
  11711. this._gl.uniform4iv(uniform, array);
  11712. };
  11713. Engine.prototype.setFloatArray = function (uniform, array) {
  11714. if (!uniform)
  11715. return;
  11716. this._gl.uniform1fv(uniform, array);
  11717. };
  11718. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11719. if (!uniform || array.length % 2 !== 0)
  11720. return;
  11721. this._gl.uniform2fv(uniform, array);
  11722. };
  11723. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11724. if (!uniform || array.length % 3 !== 0)
  11725. return;
  11726. this._gl.uniform3fv(uniform, array);
  11727. };
  11728. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11729. if (!uniform || array.length % 4 !== 0)
  11730. return;
  11731. this._gl.uniform4fv(uniform, array);
  11732. };
  11733. Engine.prototype.setArray = function (uniform, array) {
  11734. if (!uniform)
  11735. return;
  11736. this._gl.uniform1fv(uniform, array);
  11737. };
  11738. Engine.prototype.setArray2 = function (uniform, array) {
  11739. if (!uniform || array.length % 2 !== 0)
  11740. return;
  11741. this._gl.uniform2fv(uniform, array);
  11742. };
  11743. Engine.prototype.setArray3 = function (uniform, array) {
  11744. if (!uniform || array.length % 3 !== 0)
  11745. return;
  11746. this._gl.uniform3fv(uniform, array);
  11747. };
  11748. Engine.prototype.setArray4 = function (uniform, array) {
  11749. if (!uniform || array.length % 4 !== 0)
  11750. return;
  11751. this._gl.uniform4fv(uniform, array);
  11752. };
  11753. Engine.prototype.setMatrices = function (uniform, matrices) {
  11754. if (!uniform)
  11755. return;
  11756. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11757. };
  11758. Engine.prototype.setMatrix = function (uniform, matrix) {
  11759. if (!uniform)
  11760. return;
  11761. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11762. };
  11763. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11764. if (!uniform)
  11765. return;
  11766. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11767. };
  11768. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11769. if (!uniform)
  11770. return;
  11771. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11772. };
  11773. Engine.prototype.setInt = function (uniform, value) {
  11774. if (!uniform)
  11775. return;
  11776. this._gl.uniform1i(uniform, value);
  11777. };
  11778. Engine.prototype.setFloat = function (uniform, value) {
  11779. if (!uniform)
  11780. return;
  11781. this._gl.uniform1f(uniform, value);
  11782. };
  11783. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11784. if (!uniform)
  11785. return;
  11786. this._gl.uniform2f(uniform, x, y);
  11787. };
  11788. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11789. if (!uniform)
  11790. return;
  11791. this._gl.uniform3f(uniform, x, y, z);
  11792. };
  11793. Engine.prototype.setBool = function (uniform, bool) {
  11794. if (!uniform)
  11795. return;
  11796. this._gl.uniform1i(uniform, bool);
  11797. };
  11798. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11799. if (!uniform)
  11800. return;
  11801. this._gl.uniform4f(uniform, x, y, z, w);
  11802. };
  11803. Engine.prototype.setColor3 = function (uniform, color3) {
  11804. if (!uniform)
  11805. return;
  11806. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11807. };
  11808. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11809. if (!uniform)
  11810. return;
  11811. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11812. };
  11813. // States
  11814. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11815. if (zOffset === void 0) { zOffset = 0; }
  11816. if (reverseSide === void 0) { reverseSide = false; }
  11817. // Culling
  11818. if (this._depthCullingState.cull !== culling || force) {
  11819. this._depthCullingState.cull = culling;
  11820. }
  11821. // Cull face
  11822. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11823. if (this._depthCullingState.cullFace !== cullFace || force) {
  11824. this._depthCullingState.cullFace = cullFace;
  11825. }
  11826. // Z offset
  11827. this.setZOffset(zOffset);
  11828. // Front face
  11829. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11830. if (this._depthCullingState.frontFace !== frontFace || force) {
  11831. this._depthCullingState.frontFace = frontFace;
  11832. }
  11833. };
  11834. Engine.prototype.setZOffset = function (value) {
  11835. this._depthCullingState.zOffset = value;
  11836. };
  11837. Engine.prototype.getZOffset = function () {
  11838. return this._depthCullingState.zOffset;
  11839. };
  11840. Engine.prototype.setDepthBuffer = function (enable) {
  11841. this._depthCullingState.depthTest = enable;
  11842. };
  11843. Engine.prototype.getDepthWrite = function () {
  11844. return this._depthCullingState.depthMask;
  11845. };
  11846. Engine.prototype.setDepthWrite = function (enable) {
  11847. this._depthCullingState.depthMask = enable;
  11848. };
  11849. Engine.prototype.setColorWrite = function (enable) {
  11850. this._gl.colorMask(enable, enable, enable, enable);
  11851. this._colorWrite = enable;
  11852. };
  11853. Engine.prototype.getColorWrite = function () {
  11854. return this._colorWrite;
  11855. };
  11856. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11857. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11858. };
  11859. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11860. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11861. if (this._alphaMode === mode) {
  11862. return;
  11863. }
  11864. switch (mode) {
  11865. case Engine.ALPHA_DISABLE:
  11866. this._alphaState.alphaBlend = false;
  11867. break;
  11868. case Engine.ALPHA_PREMULTIPLIED:
  11869. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11870. this._alphaState.alphaBlend = true;
  11871. break;
  11872. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11873. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11874. this._alphaState.alphaBlend = true;
  11875. break;
  11876. case Engine.ALPHA_COMBINE:
  11877. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11878. this._alphaState.alphaBlend = true;
  11879. break;
  11880. case Engine.ALPHA_ONEONE:
  11881. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11882. this._alphaState.alphaBlend = true;
  11883. break;
  11884. case Engine.ALPHA_ADD:
  11885. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11886. this._alphaState.alphaBlend = true;
  11887. break;
  11888. case Engine.ALPHA_SUBTRACT:
  11889. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11890. this._alphaState.alphaBlend = true;
  11891. break;
  11892. case Engine.ALPHA_MULTIPLY:
  11893. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11894. this._alphaState.alphaBlend = true;
  11895. break;
  11896. case Engine.ALPHA_MAXIMIZED:
  11897. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11898. this._alphaState.alphaBlend = true;
  11899. break;
  11900. case Engine.ALPHA_INTERPOLATE:
  11901. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11902. this._alphaState.alphaBlend = true;
  11903. break;
  11904. case Engine.ALPHA_SCREENMODE:
  11905. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11906. this._alphaState.alphaBlend = true;
  11907. break;
  11908. }
  11909. if (!noDepthWriteChange) {
  11910. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11911. }
  11912. this._alphaMode = mode;
  11913. };
  11914. Engine.prototype.getAlphaMode = function () {
  11915. return this._alphaMode;
  11916. };
  11917. // Textures
  11918. Engine.prototype.wipeCaches = function (bruteForce) {
  11919. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11920. return;
  11921. }
  11922. this._currentEffect = null;
  11923. // 6/8/2017: deltakosh: Should not be required anymore.
  11924. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11925. if (bruteForce) {
  11926. this.resetTextureCache();
  11927. this._currentProgram = null;
  11928. this._stencilState.reset();
  11929. this._depthCullingState.reset();
  11930. this.setDepthFunctionToLessOrEqual();
  11931. this._alphaState.reset();
  11932. }
  11933. this._resetVertexBufferBinding();
  11934. this._cachedIndexBuffer = null;
  11935. this._cachedEffectForVertexBuffers = null;
  11936. this._unbindVertexArrayObject();
  11937. this.bindIndexBuffer(null);
  11938. };
  11939. /**
  11940. * Set the compressed texture format to use, based on the formats you have, and the formats
  11941. * supported by the hardware / browser.
  11942. *
  11943. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11944. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11945. * to API arguments needed to compressed textures. This puts the burden on the container
  11946. * generator to house the arcane code for determining these for current & future formats.
  11947. *
  11948. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11949. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11950. *
  11951. * Note: The result of this call is not taken into account when a texture is base64.
  11952. *
  11953. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11954. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11955. *
  11956. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11957. * @returns The extension selected.
  11958. */
  11959. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11960. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11961. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11962. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11963. return this._textureFormatInUse = this._texturesSupported[i];
  11964. }
  11965. }
  11966. }
  11967. // actively set format to nothing, to allow this to be called more than once
  11968. // and possibly fail the 2nd time
  11969. this._textureFormatInUse = null;
  11970. return null;
  11971. };
  11972. Engine.prototype._createTexture = function () {
  11973. var texture = this._gl.createTexture();
  11974. if (!texture) {
  11975. throw new Error("Unable to create texture");
  11976. }
  11977. return texture;
  11978. };
  11979. /**
  11980. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11981. * @param {string} urlArg- This contains one of the following:
  11982. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11983. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11984. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11985. *
  11986. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11987. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11988. * @param {Scene} scene- Needed for loading to the correct scene.
  11989. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11990. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11991. * @param {callback} onError- Optional callback to be called upon failure.
  11992. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11993. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11994. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11995. *
  11996. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11997. */
  11998. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11999. var _this = this;
  12000. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12001. if (onLoad === void 0) { onLoad = null; }
  12002. if (onError === void 0) { onError = null; }
  12003. if (buffer === void 0) { buffer = null; }
  12004. if (fallBack === void 0) { fallBack = null; }
  12005. if (format === void 0) { format = null; }
  12006. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12007. var fromData = url.substr(0, 5) === "data:";
  12008. var fromBlob = url.substr(0, 5) === "blob:";
  12009. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12010. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12011. // establish the file extension, if possible
  12012. var lastDot = url.lastIndexOf('.');
  12013. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12014. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12015. var isTGA = (extension.indexOf(".tga") === 0);
  12016. // determine if a ktx file should be substituted
  12017. var isKTX = false;
  12018. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12019. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12020. isKTX = true;
  12021. }
  12022. if (scene) {
  12023. scene._addPendingData(texture);
  12024. }
  12025. texture.url = url;
  12026. texture.generateMipMaps = !noMipmap;
  12027. texture.samplingMode = samplingMode;
  12028. texture.invertY = invertY;
  12029. if (!this._doNotHandleContextLost) {
  12030. // Keep a link to the buffer only if we plan to handle context lost
  12031. texture._buffer = buffer;
  12032. }
  12033. var onLoadObserver = null;
  12034. if (onLoad && !fallBack) {
  12035. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12036. }
  12037. if (!fallBack)
  12038. this._internalTexturesCache.push(texture);
  12039. var onerror = function (message, exception) {
  12040. if (scene) {
  12041. scene._removePendingData(texture);
  12042. }
  12043. if (onLoadObserver) {
  12044. texture.onLoadedObservable.remove(onLoadObserver);
  12045. }
  12046. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12047. if (isKTX) {
  12048. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12049. }
  12050. else if (BABYLON.Tools.UseFallbackTexture) {
  12051. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12052. }
  12053. if (onError) {
  12054. onError(message || "Unknown error", exception);
  12055. }
  12056. };
  12057. var callback = null;
  12058. // processing for non-image formats
  12059. if (isKTX || isTGA || isDDS) {
  12060. if (isKTX) {
  12061. callback = function (data) {
  12062. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12063. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12064. ktx.uploadLevels(_this._gl, !noMipmap);
  12065. return false;
  12066. }, samplingMode);
  12067. };
  12068. }
  12069. else if (isTGA) {
  12070. callback = function (arrayBuffer) {
  12071. var data = new Uint8Array(arrayBuffer);
  12072. var header = BABYLON.TGATools.GetTGAHeader(data);
  12073. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12074. BABYLON.TGATools.UploadContent(_this._gl, data);
  12075. return false;
  12076. }, samplingMode);
  12077. };
  12078. }
  12079. else if (isDDS) {
  12080. callback = function (data) {
  12081. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12082. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12083. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12084. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12085. return false;
  12086. }, samplingMode);
  12087. };
  12088. }
  12089. if (!buffer) {
  12090. this._loadFile(url, function (data) {
  12091. if (callback) {
  12092. callback(data);
  12093. }
  12094. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12095. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12096. });
  12097. }
  12098. else {
  12099. if (callback) {
  12100. callback(buffer);
  12101. }
  12102. }
  12103. // image format processing
  12104. }
  12105. else {
  12106. var onload = function (img) {
  12107. if (fromBlob && !_this._doNotHandleContextLost) {
  12108. // We need to store the image if we need to rebuild the texture
  12109. // in case of a webgl context lost
  12110. texture._buffer = img;
  12111. }
  12112. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12113. var gl = _this._gl;
  12114. var isPot = (img.width === potWidth && img.height === potHeight);
  12115. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12116. if (isPot) {
  12117. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12118. return false;
  12119. }
  12120. // Using shaders to rescale because canvas.drawImage is lossy
  12121. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12122. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12123. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12124. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12126. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12127. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12128. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12129. _this._releaseTexture(source);
  12130. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12131. continuationCallback();
  12132. });
  12133. return true;
  12134. }, samplingMode);
  12135. };
  12136. if (!fromData || isBase64)
  12137. if (buffer instanceof HTMLImageElement) {
  12138. onload(buffer);
  12139. }
  12140. else {
  12141. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12142. }
  12143. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12144. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12145. else
  12146. onload(buffer);
  12147. }
  12148. return texture;
  12149. };
  12150. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12151. var _this = this;
  12152. var rtt = this.createRenderTargetTexture({
  12153. width: destination.width,
  12154. height: destination.height,
  12155. }, {
  12156. generateMipMaps: false,
  12157. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12158. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12159. generateDepthBuffer: false,
  12160. generateStencilBuffer: false
  12161. });
  12162. if (!this._rescalePostProcess) {
  12163. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12164. }
  12165. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12166. _this._rescalePostProcess.onApply = function (effect) {
  12167. effect._bindTexture("textureSampler", source);
  12168. };
  12169. var hostingScene = scene;
  12170. if (!hostingScene) {
  12171. hostingScene = _this.scenes[_this.scenes.length - 1];
  12172. }
  12173. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12174. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12175. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12176. _this.unBindFramebuffer(rtt);
  12177. _this._releaseTexture(rtt);
  12178. if (onComplete) {
  12179. onComplete();
  12180. }
  12181. });
  12182. };
  12183. Engine.prototype._getInternalFormat = function (format) {
  12184. var internalFormat = this._gl.RGBA;
  12185. switch (format) {
  12186. case Engine.TEXTUREFORMAT_ALPHA:
  12187. internalFormat = this._gl.ALPHA;
  12188. break;
  12189. case Engine.TEXTUREFORMAT_LUMINANCE:
  12190. internalFormat = this._gl.LUMINANCE;
  12191. break;
  12192. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12193. internalFormat = this._gl.LUMINANCE_ALPHA;
  12194. break;
  12195. case Engine.TEXTUREFORMAT_RGB:
  12196. internalFormat = this._gl.RGB;
  12197. break;
  12198. case Engine.TEXTUREFORMAT_RGBA:
  12199. internalFormat = this._gl.RGBA;
  12200. break;
  12201. }
  12202. return internalFormat;
  12203. };
  12204. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12205. if (compression === void 0) { compression = null; }
  12206. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12207. if (!texture) {
  12208. return;
  12209. }
  12210. var internalFormat = this._getInternalFormat(format);
  12211. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12212. var textureType = this._getWebGLTextureType(type);
  12213. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12214. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12215. if (!this._doNotHandleContextLost) {
  12216. texture._bufferView = data;
  12217. texture.format = format;
  12218. texture.type = type;
  12219. texture.invertY = invertY;
  12220. texture._compression = compression;
  12221. }
  12222. if (texture.width % 4 !== 0) {
  12223. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12224. }
  12225. if (compression && data) {
  12226. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12227. }
  12228. else {
  12229. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12230. }
  12231. if (texture.generateMipMaps) {
  12232. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12233. }
  12234. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12235. // this.resetTextureCache();
  12236. texture.isReady = true;
  12237. };
  12238. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12239. if (compression === void 0) { compression = null; }
  12240. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12241. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12242. texture.baseWidth = width;
  12243. texture.baseHeight = height;
  12244. texture.width = width;
  12245. texture.height = height;
  12246. texture.format = format;
  12247. texture.generateMipMaps = generateMipMaps;
  12248. texture.samplingMode = samplingMode;
  12249. texture.invertY = invertY;
  12250. texture._compression = compression;
  12251. texture.type = type;
  12252. if (!this._doNotHandleContextLost) {
  12253. texture._bufferView = data;
  12254. }
  12255. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12256. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12257. // Filters
  12258. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12259. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12260. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12261. if (generateMipMaps) {
  12262. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12263. }
  12264. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12265. this._internalTexturesCache.push(texture);
  12266. return texture;
  12267. };
  12268. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12269. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12270. texture.baseWidth = width;
  12271. texture.baseHeight = height;
  12272. if (generateMipMaps) {
  12273. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12274. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12275. }
  12276. // this.resetTextureCache();
  12277. texture.width = width;
  12278. texture.height = height;
  12279. texture.isReady = false;
  12280. texture.generateMipMaps = generateMipMaps;
  12281. texture.samplingMode = samplingMode;
  12282. this.updateTextureSamplingMode(samplingMode, texture);
  12283. this._internalTexturesCache.push(texture);
  12284. return texture;
  12285. };
  12286. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12287. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12288. if (texture.isCube) {
  12289. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12290. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12291. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12292. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12293. }
  12294. else if (texture.is3D) {
  12295. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12296. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12297. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12298. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12299. }
  12300. else {
  12301. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12302. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12303. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12304. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12305. }
  12306. texture.samplingMode = samplingMode;
  12307. };
  12308. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12309. if (premulAlpha === void 0) { premulAlpha = false; }
  12310. if (!texture) {
  12311. return;
  12312. }
  12313. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12314. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12315. if (premulAlpha) {
  12316. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12317. }
  12318. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12319. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12320. if (texture.generateMipMaps) {
  12321. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12322. }
  12323. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12324. if (premulAlpha) {
  12325. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12326. }
  12327. texture.isReady = true;
  12328. };
  12329. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12330. if (!texture || texture._isDisabled) {
  12331. return;
  12332. }
  12333. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12334. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12335. try {
  12336. // Testing video texture support
  12337. if (this._videoTextureSupported === undefined) {
  12338. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12339. if (this._gl.getError() !== 0) {
  12340. this._videoTextureSupported = false;
  12341. }
  12342. else {
  12343. this._videoTextureSupported = true;
  12344. }
  12345. }
  12346. // Copy video through the current working canvas if video texture is not supported
  12347. if (!this._videoTextureSupported) {
  12348. if (!texture._workingCanvas) {
  12349. texture._workingCanvas = document.createElement("canvas");
  12350. var context = texture._workingCanvas.getContext("2d");
  12351. if (!context) {
  12352. throw new Error("Unable to get 2d context");
  12353. }
  12354. texture._workingContext = context;
  12355. texture._workingCanvas.width = texture.width;
  12356. texture._workingCanvas.height = texture.height;
  12357. }
  12358. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12359. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12360. }
  12361. else {
  12362. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12363. }
  12364. if (texture.generateMipMaps) {
  12365. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12366. }
  12367. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12368. // this.resetTextureCache();
  12369. texture.isReady = true;
  12370. }
  12371. catch (ex) {
  12372. // Something unexpected
  12373. // Let's disable the texture
  12374. texture._isDisabled = true;
  12375. }
  12376. };
  12377. Engine.prototype.createRenderTargetTexture = function (size, options) {
  12378. var fullOptions = new RenderTargetCreationOptions();
  12379. if (options !== undefined && typeof options === "object") {
  12380. fullOptions.generateMipMaps = options.generateMipMaps;
  12381. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12382. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  12383. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  12384. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  12385. }
  12386. else {
  12387. fullOptions.generateMipMaps = options;
  12388. fullOptions.generateDepthBuffer = true;
  12389. fullOptions.generateStencilBuffer = false;
  12390. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12391. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12392. }
  12393. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12394. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12395. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12396. }
  12397. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12398. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12399. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12400. }
  12401. var gl = this._gl;
  12402. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12403. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12404. var width = size.width || size;
  12405. var height = size.height || size;
  12406. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  12407. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12408. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12409. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12410. }
  12411. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12412. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12413. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12414. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12415. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  12416. // Create the framebuffer
  12417. var framebuffer = gl.createFramebuffer();
  12418. this.bindUnboundFramebuffer(framebuffer);
  12419. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12420. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  12421. if (fullOptions.generateMipMaps) {
  12422. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12423. }
  12424. // Unbind
  12425. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12426. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12427. this.bindUnboundFramebuffer(null);
  12428. texture._framebuffer = framebuffer;
  12429. texture.baseWidth = width;
  12430. texture.baseHeight = height;
  12431. texture.width = width;
  12432. texture.height = height;
  12433. texture.isReady = true;
  12434. texture.samples = 1;
  12435. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  12436. texture.samplingMode = fullOptions.samplingMode;
  12437. texture.type = fullOptions.type;
  12438. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  12439. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  12440. // this.resetTextureCache();
  12441. this._internalTexturesCache.push(texture);
  12442. return texture;
  12443. };
  12444. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  12445. var generateMipMaps = false;
  12446. var generateDepthBuffer = true;
  12447. var generateStencilBuffer = false;
  12448. var generateDepthTexture = false;
  12449. var textureCount = 1;
  12450. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  12451. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12452. var types = [], samplingModes = [];
  12453. if (options !== undefined) {
  12454. generateMipMaps = options.generateMipMaps;
  12455. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12456. generateStencilBuffer = options.generateStencilBuffer;
  12457. generateDepthTexture = options.generateDepthTexture;
  12458. textureCount = options.textureCount || 1;
  12459. if (options.types) {
  12460. types = options.types;
  12461. }
  12462. if (options.samplingModes) {
  12463. samplingModes = options.samplingModes;
  12464. }
  12465. }
  12466. var gl = this._gl;
  12467. // Create the framebuffer
  12468. var framebuffer = gl.createFramebuffer();
  12469. this.bindUnboundFramebuffer(framebuffer);
  12470. var width = size.width || size;
  12471. var height = size.height || size;
  12472. var textures = [];
  12473. var attachments = [];
  12474. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  12475. for (var i = 0; i < textureCount; i++) {
  12476. var samplingMode = samplingModes[i] || defaultSamplingMode;
  12477. var type = types[i] || defaultType;
  12478. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12479. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12480. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12481. }
  12482. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12483. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12484. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12485. }
  12486. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12487. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12488. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12489. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12490. }
  12491. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12492. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12493. textures.push(texture);
  12494. attachments.push(attachment);
  12495. gl.activeTexture(gl["TEXTURE" + i]);
  12496. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  12497. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12498. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12501. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12502. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12503. if (generateMipMaps) {
  12504. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12505. }
  12506. // Unbind
  12507. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12508. texture._framebuffer = framebuffer;
  12509. texture._depthStencilBuffer = depthStencilBuffer;
  12510. texture.baseWidth = width;
  12511. texture.baseHeight = height;
  12512. texture.width = width;
  12513. texture.height = height;
  12514. texture.isReady = true;
  12515. texture.samples = 1;
  12516. texture.generateMipMaps = generateMipMaps;
  12517. texture.samplingMode = samplingMode;
  12518. texture.type = type;
  12519. texture._generateDepthBuffer = generateDepthBuffer;
  12520. texture._generateStencilBuffer = generateStencilBuffer;
  12521. texture._attachments = attachments;
  12522. this._internalTexturesCache.push(texture);
  12523. }
  12524. if (generateDepthTexture && this._caps.depthTextureExtension) {
  12525. // Depth texture
  12526. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12527. gl.activeTexture(gl.TEXTURE0);
  12528. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  12529. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12530. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12531. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12532. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12533. 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);
  12534. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  12535. depthTexture._framebuffer = framebuffer;
  12536. depthTexture.baseWidth = width;
  12537. depthTexture.baseHeight = height;
  12538. depthTexture.width = width;
  12539. depthTexture.height = height;
  12540. depthTexture.isReady = true;
  12541. depthTexture.samples = 1;
  12542. depthTexture.generateMipMaps = generateMipMaps;
  12543. depthTexture.samplingMode = gl.NEAREST;
  12544. depthTexture._generateDepthBuffer = generateDepthBuffer;
  12545. depthTexture._generateStencilBuffer = generateStencilBuffer;
  12546. textures.push(depthTexture);
  12547. this._internalTexturesCache.push(depthTexture);
  12548. }
  12549. gl.drawBuffers(attachments);
  12550. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12551. this.bindUnboundFramebuffer(null);
  12552. this.resetTextureCache();
  12553. return textures;
  12554. };
  12555. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  12556. if (samples === void 0) { samples = 1; }
  12557. var depthStencilBuffer = null;
  12558. var gl = this._gl;
  12559. // Create the depth/stencil buffer
  12560. if (generateStencilBuffer) {
  12561. depthStencilBuffer = gl.createRenderbuffer();
  12562. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12563. if (samples > 1) {
  12564. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  12565. }
  12566. else {
  12567. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  12568. }
  12569. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12570. }
  12571. else if (generateDepthBuffer) {
  12572. depthStencilBuffer = gl.createRenderbuffer();
  12573. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12574. if (samples > 1) {
  12575. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12576. }
  12577. else {
  12578. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12579. }
  12580. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12581. }
  12582. return depthStencilBuffer;
  12583. };
  12584. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12585. if (this.webGLVersion < 2 || !texture) {
  12586. return 1;
  12587. }
  12588. if (texture.samples === samples) {
  12589. return samples;
  12590. }
  12591. var gl = this._gl;
  12592. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12593. // Dispose previous render buffers
  12594. if (texture._depthStencilBuffer) {
  12595. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12596. texture._depthStencilBuffer = null;
  12597. }
  12598. if (texture._MSAAFramebuffer) {
  12599. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12600. texture._MSAAFramebuffer = null;
  12601. }
  12602. if (texture._MSAARenderBuffer) {
  12603. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12604. texture._MSAARenderBuffer = null;
  12605. }
  12606. if (samples > 1) {
  12607. var framebuffer = gl.createFramebuffer();
  12608. if (!framebuffer) {
  12609. throw new Error("Unable to create multi sampled framebuffer");
  12610. }
  12611. texture._MSAAFramebuffer = framebuffer;
  12612. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12613. var colorRenderbuffer = gl.createRenderbuffer();
  12614. if (!colorRenderbuffer) {
  12615. throw new Error("Unable to create multi sampled framebuffer");
  12616. }
  12617. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12618. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12619. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12620. texture._MSAARenderBuffer = colorRenderbuffer;
  12621. }
  12622. else {
  12623. this.bindUnboundFramebuffer(texture._framebuffer);
  12624. }
  12625. texture.samples = samples;
  12626. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12627. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12628. this.bindUnboundFramebuffer(null);
  12629. return samples;
  12630. };
  12631. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12632. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12633. return 1;
  12634. }
  12635. if (textures[0].samples === samples) {
  12636. return samples;
  12637. }
  12638. var gl = this._gl;
  12639. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12640. // Dispose previous render buffers
  12641. if (textures[0]._depthStencilBuffer) {
  12642. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12643. textures[0]._depthStencilBuffer = null;
  12644. }
  12645. if (textures[0]._MSAAFramebuffer) {
  12646. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12647. textures[0]._MSAAFramebuffer = null;
  12648. }
  12649. for (var i = 0; i < textures.length; i++) {
  12650. if (textures[i]._MSAARenderBuffer) {
  12651. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12652. textures[i]._MSAARenderBuffer = null;
  12653. }
  12654. }
  12655. if (samples > 1) {
  12656. var framebuffer = gl.createFramebuffer();
  12657. if (!framebuffer) {
  12658. throw new Error("Unable to create multi sampled framebuffer");
  12659. }
  12660. this.bindUnboundFramebuffer(framebuffer);
  12661. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12662. var attachments = [];
  12663. for (var i = 0; i < textures.length; i++) {
  12664. var texture = textures[i];
  12665. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12666. var colorRenderbuffer = gl.createRenderbuffer();
  12667. if (!colorRenderbuffer) {
  12668. throw new Error("Unable to create multi sampled framebuffer");
  12669. }
  12670. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12671. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12672. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12673. texture._MSAAFramebuffer = framebuffer;
  12674. texture._MSAARenderBuffer = colorRenderbuffer;
  12675. texture.samples = samples;
  12676. texture._depthStencilBuffer = depthStencilBuffer;
  12677. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12678. attachments.push(attachment);
  12679. }
  12680. gl.drawBuffers(attachments);
  12681. }
  12682. else {
  12683. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12684. }
  12685. this.bindUnboundFramebuffer(null);
  12686. return samples;
  12687. };
  12688. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12689. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12690. };
  12691. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12692. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12693. };
  12694. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12695. var gl = this._gl;
  12696. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12697. var generateMipMaps = true;
  12698. var generateDepthBuffer = true;
  12699. var generateStencilBuffer = false;
  12700. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12701. if (options !== undefined) {
  12702. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12703. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12704. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12705. if (options.samplingMode !== undefined) {
  12706. samplingMode = options.samplingMode;
  12707. }
  12708. }
  12709. texture.isCube = true;
  12710. texture.generateMipMaps = generateMipMaps;
  12711. texture.samples = 1;
  12712. texture.samplingMode = samplingMode;
  12713. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12714. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12715. for (var face = 0; face < 6; face++) {
  12716. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12717. }
  12718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12722. // Create the framebuffer
  12723. var framebuffer = gl.createFramebuffer();
  12724. this.bindUnboundFramebuffer(framebuffer);
  12725. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12726. // Mipmaps
  12727. if (texture.generateMipMaps) {
  12728. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12729. }
  12730. // Unbind
  12731. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12732. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12733. this.bindUnboundFramebuffer(null);
  12734. texture._framebuffer = framebuffer;
  12735. texture.width = size;
  12736. texture.height = size;
  12737. texture.isReady = true;
  12738. //this.resetTextureCache();
  12739. this._internalTexturesCache.push(texture);
  12740. return texture;
  12741. };
  12742. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12743. var _this = this;
  12744. if (onLoad === void 0) { onLoad = null; }
  12745. if (onError === void 0) { onError = null; }
  12746. if (forcedExtension === void 0) { forcedExtension = null; }
  12747. var callback = function (loadData) {
  12748. if (!loadData) {
  12749. if (onLoad) {
  12750. onLoad(null);
  12751. }
  12752. return;
  12753. }
  12754. var texture = loadData.texture;
  12755. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12756. texture._lodGenerationScale = scale;
  12757. texture._lodGenerationOffset = offset;
  12758. if (_this._caps.textureLOD) {
  12759. // Do not add extra process if texture lod is supported.
  12760. if (onLoad) {
  12761. onLoad(texture);
  12762. }
  12763. return;
  12764. }
  12765. var mipSlices = 3;
  12766. var gl = _this._gl;
  12767. var width = loadData.width;
  12768. if (!width) {
  12769. return;
  12770. }
  12771. var textures = [];
  12772. for (var i = 0; i < mipSlices; i++) {
  12773. //compute LOD from even spacing in smoothness (matching shader calculation)
  12774. var smoothness = i / (mipSlices - 1);
  12775. var roughness = 1 - smoothness;
  12776. var minLODIndex = offset; // roughness = 0
  12777. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12778. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12779. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12780. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12781. glTextureFromLod.isCube = true;
  12782. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12783. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12784. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12785. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12786. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12787. if (loadData.isDDS) {
  12788. var info = loadData.info;
  12789. var data = loadData.data;
  12790. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12791. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12792. }
  12793. else {
  12794. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12795. }
  12796. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12797. // Wrap in a base texture for easy binding.
  12798. var lodTexture = new BABYLON.BaseTexture(scene);
  12799. lodTexture.isCube = true;
  12800. lodTexture._texture = glTextureFromLod;
  12801. glTextureFromLod.isReady = true;
  12802. textures.push(lodTexture);
  12803. }
  12804. texture._lodTextureHigh = textures[2];
  12805. texture._lodTextureMid = textures[1];
  12806. texture._lodTextureLow = textures[0];
  12807. if (onLoad) {
  12808. onLoad(texture);
  12809. }
  12810. };
  12811. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12812. };
  12813. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12814. var _this = this;
  12815. if (onLoad === void 0) { onLoad = null; }
  12816. if (onError === void 0) { onError = null; }
  12817. if (forcedExtension === void 0) { forcedExtension = null; }
  12818. var gl = this._gl;
  12819. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12820. texture.isCube = true;
  12821. texture.url = rootUrl;
  12822. texture.generateMipMaps = !noMipmap;
  12823. if (!this._doNotHandleContextLost) {
  12824. texture._extension = forcedExtension;
  12825. texture._files = files;
  12826. }
  12827. var isKTX = false;
  12828. var isDDS = false;
  12829. var lastDot = rootUrl.lastIndexOf('.');
  12830. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12831. if (this._textureFormatInUse) {
  12832. extension = this._textureFormatInUse;
  12833. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12834. isKTX = true;
  12835. }
  12836. else {
  12837. isDDS = (extension === ".dds");
  12838. }
  12839. var onerror = function (request, exception) {
  12840. if (onError && request) {
  12841. onError(request.status + " " + request.statusText, exception);
  12842. }
  12843. };
  12844. if (isKTX) {
  12845. this._loadFile(rootUrl, function (data) {
  12846. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12847. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12848. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12849. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12850. ktx.uploadLevels(_this._gl, !noMipmap);
  12851. _this.setCubeMapTextureParams(gl, loadMipmap);
  12852. texture.width = ktx.pixelWidth;
  12853. texture.height = ktx.pixelHeight;
  12854. texture.isReady = true;
  12855. }, undefined, undefined, true, onerror);
  12856. }
  12857. else if (isDDS) {
  12858. if (files && files.length === 6) {
  12859. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12860. var info;
  12861. var loadMipmap = false;
  12862. var width = 0;
  12863. for (var index = 0; index < imgs.length; index++) {
  12864. var data = imgs[index];
  12865. info = BABYLON.DDSTools.GetDDSInfo(data);
  12866. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12867. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12868. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12869. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12870. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12871. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12872. }
  12873. texture.width = info.width;
  12874. texture.height = info.height;
  12875. texture.type = info.textureType;
  12876. width = info.width;
  12877. }
  12878. _this.setCubeMapTextureParams(gl, loadMipmap);
  12879. texture.isReady = true;
  12880. if (onLoad) {
  12881. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12882. }
  12883. }, files, onError);
  12884. }
  12885. else {
  12886. this._loadFile(rootUrl, function (data) {
  12887. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12888. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12889. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12890. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12891. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12892. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12893. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12894. }
  12895. _this.setCubeMapTextureParams(gl, loadMipmap);
  12896. texture.width = info.width;
  12897. texture.height = info.height;
  12898. texture.isReady = true;
  12899. texture.type = info.textureType;
  12900. if (onLoad) {
  12901. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12902. }
  12903. }, undefined, undefined, true, onerror);
  12904. }
  12905. }
  12906. else {
  12907. if (!files) {
  12908. throw new Error("Cannot load cubemap because files were not defined");
  12909. }
  12910. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12911. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12912. var height = width;
  12913. _this._prepareWorkingCanvas();
  12914. if (!_this._workingCanvas || !_this._workingContext) {
  12915. return;
  12916. }
  12917. _this._workingCanvas.width = width;
  12918. _this._workingCanvas.height = height;
  12919. var faces = [
  12920. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12921. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12922. ];
  12923. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12924. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12925. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12926. for (var index = 0; index < faces.length; index++) {
  12927. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12928. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12929. }
  12930. if (!noMipmap) {
  12931. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12932. }
  12933. _this.setCubeMapTextureParams(gl, !noMipmap);
  12934. texture.width = width;
  12935. texture.height = height;
  12936. texture.isReady = true;
  12937. if (format) {
  12938. texture.format = format;
  12939. }
  12940. texture.onLoadedObservable.notifyObservers(texture);
  12941. texture.onLoadedObservable.clear();
  12942. if (onLoad) {
  12943. onLoad();
  12944. }
  12945. }, files, onError);
  12946. }
  12947. this._internalTexturesCache.push(texture);
  12948. return texture;
  12949. };
  12950. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12953. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12954. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12955. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12956. // this.resetTextureCache();
  12957. };
  12958. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12959. if (compression === void 0) { compression = null; }
  12960. if (level === void 0) { level = 0; }
  12961. texture._bufferViewArray = data;
  12962. texture.format = format;
  12963. texture.type = type;
  12964. texture.invertY = invertY;
  12965. texture._compression = compression;
  12966. var gl = this._gl;
  12967. var textureType = this._getWebGLTextureType(type);
  12968. var internalFormat = this._getInternalFormat(format);
  12969. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12970. var needConversion = false;
  12971. if (internalFormat === gl.RGB) {
  12972. internalFormat = gl.RGBA;
  12973. needConversion = true;
  12974. }
  12975. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12976. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12977. if (texture.width % 4 !== 0) {
  12978. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12979. }
  12980. // Data are known to be in +X +Y +Z -X -Y -Z
  12981. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12982. var faceData = data[faceIndex];
  12983. if (compression) {
  12984. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12985. }
  12986. else {
  12987. if (needConversion) {
  12988. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12989. }
  12990. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12991. }
  12992. }
  12993. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12994. if (isPot && texture.generateMipMaps && level === 0) {
  12995. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12996. }
  12997. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12998. // this.resetTextureCache();
  12999. texture.isReady = true;
  13000. };
  13001. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13002. if (compression === void 0) { compression = null; }
  13003. var gl = this._gl;
  13004. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13005. texture.isCube = true;
  13006. texture.generateMipMaps = generateMipMaps;
  13007. texture.format = format;
  13008. texture.type = type;
  13009. if (!this._doNotHandleContextLost) {
  13010. texture._bufferViewArray = data;
  13011. }
  13012. var textureType = this._getWebGLTextureType(type);
  13013. var internalFormat = this._getInternalFormat(format);
  13014. if (internalFormat === gl.RGB) {
  13015. internalFormat = gl.RGBA;
  13016. }
  13017. var width = size;
  13018. var height = width;
  13019. texture.width = width;
  13020. texture.height = height;
  13021. // Double check on POT to generate Mips.
  13022. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13023. if (!isPot) {
  13024. generateMipMaps = false;
  13025. }
  13026. // Upload data if needed. The texture won't be ready until then.
  13027. if (data) {
  13028. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13029. }
  13030. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13031. // Filters
  13032. if (data && generateMipMaps) {
  13033. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13034. }
  13035. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13036. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13037. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13038. }
  13039. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13040. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13041. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13042. }
  13043. else {
  13044. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13045. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13046. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13047. }
  13048. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13049. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13050. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13051. return texture;
  13052. };
  13053. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13054. var _this = this;
  13055. if (onLoad === void 0) { onLoad = null; }
  13056. if (onError === void 0) { onError = null; }
  13057. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13058. if (invertY === void 0) { invertY = false; }
  13059. var gl = this._gl;
  13060. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13061. scene._addPendingData(texture);
  13062. texture.url = url;
  13063. this._internalTexturesCache.push(texture);
  13064. var onerror = function (request, exception) {
  13065. scene._removePendingData(texture);
  13066. if (onError && request) {
  13067. onError(request.status + " " + request.statusText, exception);
  13068. }
  13069. };
  13070. var internalCallback = function (data) {
  13071. var width = texture.width;
  13072. var faceDataArrays = callback(data);
  13073. if (!faceDataArrays) {
  13074. return;
  13075. }
  13076. if (mipmmapGenerator) {
  13077. var textureType = _this._getWebGLTextureType(type);
  13078. var internalFormat = _this._getInternalFormat(format);
  13079. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13080. var needConversion = false;
  13081. if (internalFormat === gl.RGB) {
  13082. internalFormat = gl.RGBA;
  13083. needConversion = true;
  13084. }
  13085. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13086. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13087. var mipData = mipmmapGenerator(faceDataArrays);
  13088. for (var level = 0; level < mipData.length; level++) {
  13089. var mipSize = width >> level;
  13090. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13091. var mipFaceData = mipData[level][faceIndex];
  13092. if (needConversion) {
  13093. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13094. }
  13095. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13096. }
  13097. }
  13098. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13099. }
  13100. else {
  13101. texture.generateMipMaps = !noMipmap;
  13102. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13103. }
  13104. texture.isReady = true;
  13105. // this.resetTextureCache();
  13106. scene._removePendingData(texture);
  13107. if (onLoad) {
  13108. onLoad();
  13109. }
  13110. };
  13111. this._loadFile(url, function (data) {
  13112. internalCallback(data);
  13113. }, undefined, scene.database, true, onerror);
  13114. return texture;
  13115. };
  13116. ;
  13117. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13118. if (compression === void 0) { compression = null; }
  13119. var internalFormat = this._getInternalFormat(format);
  13120. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13121. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13122. if (!this._doNotHandleContextLost) {
  13123. texture._bufferView = data;
  13124. texture.format = format;
  13125. texture.invertY = invertY;
  13126. texture._compression = compression;
  13127. }
  13128. if (texture.width % 4 !== 0) {
  13129. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13130. }
  13131. if (compression && data) {
  13132. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13133. }
  13134. else {
  13135. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13136. }
  13137. if (texture.generateMipMaps) {
  13138. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13139. }
  13140. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13141. // this.resetTextureCache();
  13142. texture.isReady = true;
  13143. };
  13144. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13145. if (compression === void 0) { compression = null; }
  13146. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13147. texture.baseWidth = width;
  13148. texture.baseHeight = height;
  13149. texture.baseDepth = depth;
  13150. texture.width = width;
  13151. texture.height = height;
  13152. texture.depth = depth;
  13153. texture.format = format;
  13154. texture.generateMipMaps = generateMipMaps;
  13155. texture.samplingMode = samplingMode;
  13156. texture.is3D = true;
  13157. if (!this._doNotHandleContextLost) {
  13158. texture._bufferView = data;
  13159. }
  13160. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13161. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13162. // Filters
  13163. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13164. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13165. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13166. if (generateMipMaps) {
  13167. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13168. }
  13169. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13170. this._internalTexturesCache.push(texture);
  13171. return texture;
  13172. };
  13173. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13174. var gl = this._gl;
  13175. if (!gl) {
  13176. return;
  13177. }
  13178. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13179. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13180. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13181. if (!noMipmap && !isCompressed) {
  13182. gl.generateMipmap(gl.TEXTURE_2D);
  13183. }
  13184. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13185. // this.resetTextureCache();
  13186. if (scene) {
  13187. scene._removePendingData(texture);
  13188. }
  13189. texture.onLoadedObservable.notifyObservers(texture);
  13190. texture.onLoadedObservable.clear();
  13191. };
  13192. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13193. var _this = this;
  13194. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13195. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13196. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13197. var gl = this._gl;
  13198. if (!gl) {
  13199. return;
  13200. }
  13201. if (!texture._webGLTexture) {
  13202. // this.resetTextureCache();
  13203. if (scene) {
  13204. scene._removePendingData(texture);
  13205. }
  13206. return;
  13207. }
  13208. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13209. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13210. texture.baseWidth = width;
  13211. texture.baseHeight = height;
  13212. texture.width = potWidth;
  13213. texture.height = potHeight;
  13214. texture.isReady = true;
  13215. if (processFunction(potWidth, potHeight, function () {
  13216. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13217. })) {
  13218. // Returning as texture needs extra async steps
  13219. return;
  13220. }
  13221. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13222. };
  13223. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13224. // Create new RGBA data container.
  13225. var rgbaData;
  13226. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13227. rgbaData = new Float32Array(width * height * 4);
  13228. }
  13229. else {
  13230. rgbaData = new Uint32Array(width * height * 4);
  13231. }
  13232. // Convert each pixel.
  13233. for (var x = 0; x < width; x++) {
  13234. for (var y = 0; y < height; y++) {
  13235. var index = (y * width + x) * 3;
  13236. var newIndex = (y * width + x) * 4;
  13237. // Map Old Value to new value.
  13238. rgbaData[newIndex + 0] = rgbData[index + 0];
  13239. rgbaData[newIndex + 1] = rgbData[index + 1];
  13240. rgbaData[newIndex + 2] = rgbData[index + 2];
  13241. // Add fully opaque alpha channel.
  13242. rgbaData[newIndex + 3] = 1;
  13243. }
  13244. }
  13245. return rgbaData;
  13246. };
  13247. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13248. var gl = this._gl;
  13249. if (texture._framebuffer) {
  13250. gl.deleteFramebuffer(texture._framebuffer);
  13251. texture._framebuffer = null;
  13252. }
  13253. if (texture._depthStencilBuffer) {
  13254. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13255. texture._depthStencilBuffer = null;
  13256. }
  13257. if (texture._MSAAFramebuffer) {
  13258. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13259. texture._MSAAFramebuffer = null;
  13260. }
  13261. if (texture._MSAARenderBuffer) {
  13262. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13263. texture._MSAARenderBuffer = null;
  13264. }
  13265. };
  13266. Engine.prototype._releaseTexture = function (texture) {
  13267. var gl = this._gl;
  13268. this._releaseFramebufferObjects(texture);
  13269. gl.deleteTexture(texture._webGLTexture);
  13270. // Unbind channels
  13271. this.unbindAllTextures();
  13272. var index = this._internalTexturesCache.indexOf(texture);
  13273. if (index !== -1) {
  13274. this._internalTexturesCache.splice(index, 1);
  13275. }
  13276. // Integrated fixed lod samplers.
  13277. if (texture._lodTextureHigh) {
  13278. texture._lodTextureHigh.dispose();
  13279. }
  13280. if (texture._lodTextureMid) {
  13281. texture._lodTextureMid.dispose();
  13282. }
  13283. if (texture._lodTextureLow) {
  13284. texture._lodTextureLow.dispose();
  13285. }
  13286. };
  13287. Engine.prototype.setProgram = function (program) {
  13288. if (this._currentProgram !== program) {
  13289. this._gl.useProgram(program);
  13290. this._currentProgram = program;
  13291. }
  13292. };
  13293. Engine.prototype.bindSamplers = function (effect) {
  13294. this.setProgram(effect.getProgram());
  13295. var samplers = effect.getSamplers();
  13296. for (var index = 0; index < samplers.length; index++) {
  13297. var uniform = effect.getUniform(samplers[index]);
  13298. if (uniform) {
  13299. this._boundUniforms[index] = uniform;
  13300. }
  13301. }
  13302. this._currentEffect = null;
  13303. };
  13304. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13305. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13306. return;
  13307. }
  13308. // Remove
  13309. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13310. // Bind last to it
  13311. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13312. // Bind to dummy
  13313. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13314. };
  13315. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13316. if (!internalTexture) {
  13317. return -1;
  13318. }
  13319. internalTexture._initialSlot = channel;
  13320. if (this.disableTextureBindingOptimization) {
  13321. if (channel !== internalTexture._designatedSlot) {
  13322. this._textureCollisions.addCount(1, false);
  13323. }
  13324. }
  13325. else {
  13326. if (channel !== internalTexture._designatedSlot) {
  13327. if (internalTexture._designatedSlot > -1) {
  13328. return internalTexture._designatedSlot;
  13329. }
  13330. else {
  13331. // No slot for this texture, let's pick a new one (if we find a free slot)
  13332. if (this._nextFreeTextureSlots.length) {
  13333. return this._nextFreeTextureSlots[0];
  13334. }
  13335. // We need to recycle the oldest bound texture, sorry.
  13336. this._textureCollisions.addCount(1, false);
  13337. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13338. }
  13339. }
  13340. }
  13341. return channel;
  13342. };
  13343. Engine.prototype._linkTrackers = function (previous, next) {
  13344. previous.next = next;
  13345. next.previous = previous;
  13346. };
  13347. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  13348. var currentSlot = internalTexture._designatedSlot;
  13349. if (currentSlot === -1) {
  13350. return -1;
  13351. }
  13352. internalTexture._designatedSlot = -1;
  13353. if (this.disableTextureBindingOptimization) {
  13354. return -1;
  13355. }
  13356. // Remove from bound list
  13357. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13358. // Free the slot
  13359. this._boundTexturesCache[currentSlot] = null;
  13360. this._nextFreeTextureSlots.push(currentSlot);
  13361. return currentSlot;
  13362. };
  13363. Engine.prototype._activateCurrentTexture = function () {
  13364. if (this._currentTextureChannel !== this._activeChannel) {
  13365. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  13366. this._currentTextureChannel = this._activeChannel;
  13367. }
  13368. };
  13369. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  13370. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  13371. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  13372. this._activeChannel = texture._designatedSlot;
  13373. }
  13374. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  13375. var isTextureForRendering = texture && texture._initialSlot > -1;
  13376. if (currentTextureBound !== texture) {
  13377. if (currentTextureBound) {
  13378. this._removeDesignatedSlot(currentTextureBound);
  13379. }
  13380. this._activateCurrentTexture();
  13381. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  13382. this._boundTexturesCache[this._activeChannel] = texture;
  13383. if (texture) {
  13384. if (!this.disableTextureBindingOptimization) {
  13385. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  13386. if (slotIndex > -1) {
  13387. this._nextFreeTextureSlots.splice(slotIndex, 1);
  13388. }
  13389. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  13390. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  13391. }
  13392. texture._designatedSlot = this._activeChannel;
  13393. }
  13394. }
  13395. else if (forTextureDataUpdate) {
  13396. this._activateCurrentTexture();
  13397. }
  13398. if (isTextureForRendering && !forTextureDataUpdate) {
  13399. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  13400. }
  13401. };
  13402. Engine.prototype._bindTexture = function (channel, texture) {
  13403. if (channel < 0) {
  13404. return;
  13405. }
  13406. if (texture) {
  13407. channel = this._getCorrectTextureChannel(channel, texture);
  13408. }
  13409. this._activeChannel = channel;
  13410. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  13411. };
  13412. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13413. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  13414. };
  13415. Engine.prototype.unbindAllTextures = function () {
  13416. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  13417. this._activeChannel = channel;
  13418. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13419. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13420. if (this.webGLVersion > 1) {
  13421. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13422. }
  13423. }
  13424. };
  13425. Engine.prototype.setTexture = function (channel, uniform, texture) {
  13426. if (channel < 0) {
  13427. return;
  13428. }
  13429. if (uniform) {
  13430. this._boundUniforms[channel] = uniform;
  13431. }
  13432. this._setTexture(channel, texture);
  13433. };
  13434. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  13435. var uniform = this._boundUniforms[sourceSlot];
  13436. if (uniform._currentState === destination) {
  13437. return;
  13438. }
  13439. this._gl.uniform1i(uniform, destination);
  13440. uniform._currentState = destination;
  13441. };
  13442. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  13443. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  13444. // Not ready?
  13445. if (!texture) {
  13446. if (this._boundTexturesCache[channel] != null) {
  13447. this._activeChannel = channel;
  13448. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13449. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13450. if (this.webGLVersion > 1) {
  13451. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13452. }
  13453. }
  13454. return false;
  13455. }
  13456. // Video
  13457. if (texture.video) {
  13458. this._activeChannel = channel;
  13459. texture.update();
  13460. }
  13461. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  13462. texture.delayLoad();
  13463. return false;
  13464. }
  13465. var internalTexture;
  13466. if (texture.isReady()) {
  13467. internalTexture = texture.getInternalTexture();
  13468. }
  13469. else if (texture.isCube) {
  13470. internalTexture = this.emptyCubeTexture;
  13471. }
  13472. else if (texture.is3D) {
  13473. internalTexture = this.emptyTexture3D;
  13474. }
  13475. else {
  13476. internalTexture = this.emptyTexture;
  13477. }
  13478. if (!isPartOfTextureArray) {
  13479. channel = this._getCorrectTextureChannel(channel, internalTexture);
  13480. }
  13481. if (this._boundTexturesCache[channel] === internalTexture) {
  13482. this._moveBoundTextureOnTop(internalTexture);
  13483. if (!isPartOfTextureArray) {
  13484. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  13485. }
  13486. return false;
  13487. }
  13488. this._activeChannel = channel;
  13489. if (internalTexture && internalTexture.is3D) {
  13490. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  13491. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13492. internalTexture._cachedWrapU = texture.wrapU;
  13493. switch (texture.wrapU) {
  13494. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13495. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13496. break;
  13497. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13498. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13499. break;
  13500. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13501. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13502. break;
  13503. }
  13504. }
  13505. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13506. internalTexture._cachedWrapV = texture.wrapV;
  13507. switch (texture.wrapV) {
  13508. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13509. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13510. break;
  13511. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13512. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13513. break;
  13514. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13515. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13516. break;
  13517. }
  13518. }
  13519. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  13520. internalTexture._cachedWrapR = texture.wrapR;
  13521. switch (texture.wrapV) {
  13522. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13523. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  13524. break;
  13525. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13526. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  13527. break;
  13528. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13529. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  13530. break;
  13531. }
  13532. }
  13533. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  13534. }
  13535. else if (internalTexture && internalTexture.isCube) {
  13536. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  13537. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  13538. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  13539. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  13540. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  13541. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  13542. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  13543. }
  13544. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  13545. }
  13546. else {
  13547. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  13548. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13549. internalTexture._cachedWrapU = texture.wrapU;
  13550. switch (texture.wrapU) {
  13551. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13552. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13553. break;
  13554. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13555. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13556. break;
  13557. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13558. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13559. break;
  13560. }
  13561. }
  13562. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13563. internalTexture._cachedWrapV = texture.wrapV;
  13564. switch (texture.wrapV) {
  13565. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13566. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13567. break;
  13568. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13569. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13570. break;
  13571. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13572. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13573. break;
  13574. }
  13575. }
  13576. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13577. }
  13578. return true;
  13579. };
  13580. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13581. if (channel < 0 || !uniform) {
  13582. return;
  13583. }
  13584. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13585. this._textureUnits = new Int32Array(textures.length);
  13586. }
  13587. for (var i = 0; i < textures.length; i++) {
  13588. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13589. }
  13590. this._gl.uniform1iv(uniform, this._textureUnits);
  13591. for (var index = 0; index < textures.length; index++) {
  13592. this._setTexture(this._textureUnits[index], textures[index], true);
  13593. }
  13594. };
  13595. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13596. var internalTexture = texture.getInternalTexture();
  13597. if (!internalTexture) {
  13598. return;
  13599. }
  13600. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13601. var value = texture.anisotropicFilteringLevel;
  13602. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13603. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13604. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13605. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13606. }
  13607. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13608. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13609. internalTexture._cachedAnisotropicFilteringLevel = value;
  13610. }
  13611. };
  13612. Engine.prototype.readPixels = function (x, y, width, height) {
  13613. var data = new Uint8Array(height * width * 4);
  13614. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13615. return data;
  13616. };
  13617. /**
  13618. * Add an externaly attached data from its key.
  13619. * This method call will fail and return false, if such key already exists.
  13620. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13621. * @param key the unique key that identifies the data
  13622. * @param data the data object to associate to the key for this Engine instance
  13623. * @return true if no such key were already present and the data was added successfully, false otherwise
  13624. */
  13625. Engine.prototype.addExternalData = function (key, data) {
  13626. if (!this._externalData) {
  13627. this._externalData = new BABYLON.StringDictionary();
  13628. }
  13629. return this._externalData.add(key, data);
  13630. };
  13631. /**
  13632. * Get an externaly attached data from its key
  13633. * @param key the unique key that identifies the data
  13634. * @return the associated data, if present (can be null), or undefined if not present
  13635. */
  13636. Engine.prototype.getExternalData = function (key) {
  13637. if (!this._externalData) {
  13638. this._externalData = new BABYLON.StringDictionary();
  13639. }
  13640. return this._externalData.get(key);
  13641. };
  13642. /**
  13643. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13644. * @param key the unique key that identifies the data
  13645. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13646. * @return the associated data, can be null if the factory returned null.
  13647. */
  13648. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13649. if (!this._externalData) {
  13650. this._externalData = new BABYLON.StringDictionary();
  13651. }
  13652. return this._externalData.getOrAddWithFactory(key, factory);
  13653. };
  13654. /**
  13655. * Remove an externaly attached data from the Engine instance
  13656. * @param key the unique key that identifies the data
  13657. * @return true if the data was successfully removed, false if it doesn't exist
  13658. */
  13659. Engine.prototype.removeExternalData = function (key) {
  13660. if (!this._externalData) {
  13661. this._externalData = new BABYLON.StringDictionary();
  13662. }
  13663. return this._externalData.remove(key);
  13664. };
  13665. Engine.prototype.unbindAllAttributes = function () {
  13666. if (this._mustWipeVertexAttributes) {
  13667. this._mustWipeVertexAttributes = false;
  13668. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13669. this._gl.disableVertexAttribArray(i);
  13670. this._vertexAttribArraysEnabled[i] = false;
  13671. this._currentBufferPointers[i].active = false;
  13672. }
  13673. return;
  13674. }
  13675. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13676. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13677. continue;
  13678. }
  13679. this._gl.disableVertexAttribArray(i);
  13680. this._vertexAttribArraysEnabled[i] = false;
  13681. this._currentBufferPointers[i].active = false;
  13682. }
  13683. };
  13684. Engine.prototype.releaseEffects = function () {
  13685. for (var name in this._compiledEffects) {
  13686. this._deleteProgram(this._compiledEffects[name]._program);
  13687. }
  13688. this._compiledEffects = {};
  13689. };
  13690. // Dispose
  13691. Engine.prototype.dispose = function () {
  13692. this.hideLoadingUI();
  13693. this.stopRenderLoop();
  13694. // Release postProcesses
  13695. while (this.postProcesses.length) {
  13696. this.postProcesses[0].dispose();
  13697. }
  13698. // Empty texture
  13699. if (this._emptyTexture) {
  13700. this._releaseTexture(this._emptyTexture);
  13701. this._emptyTexture = null;
  13702. }
  13703. if (this._emptyCubeTexture) {
  13704. this._releaseTexture(this._emptyCubeTexture);
  13705. this._emptyCubeTexture = null;
  13706. }
  13707. // Rescale PP
  13708. if (this._rescalePostProcess) {
  13709. this._rescalePostProcess.dispose();
  13710. }
  13711. // Release scenes
  13712. while (this.scenes.length) {
  13713. this.scenes[0].dispose();
  13714. }
  13715. // Release audio engine
  13716. if (Engine.audioEngine) {
  13717. Engine.audioEngine.dispose();
  13718. }
  13719. // Release effects
  13720. this.releaseEffects();
  13721. // Unbind
  13722. this.unbindAllAttributes();
  13723. if (this._dummyFramebuffer) {
  13724. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13725. }
  13726. //WebVR
  13727. this.disableVR();
  13728. // Events
  13729. if (BABYLON.Tools.IsWindowObjectExist()) {
  13730. window.removeEventListener("blur", this._onBlur);
  13731. window.removeEventListener("focus", this._onFocus);
  13732. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13733. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13734. if (this._renderingCanvas) {
  13735. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13736. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13737. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13738. if (!this._doNotHandleContextLost) {
  13739. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13740. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13741. }
  13742. }
  13743. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13744. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13745. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13746. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13747. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13748. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13749. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13750. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13751. if (this._onVrDisplayConnect) {
  13752. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13753. if (this._onVrDisplayDisconnect) {
  13754. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13755. }
  13756. if (this._onVrDisplayPresentChange) {
  13757. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13758. }
  13759. this._onVrDisplayConnect = null;
  13760. this._onVrDisplayDisconnect = null;
  13761. }
  13762. }
  13763. // Remove from Instances
  13764. var index = Engine.Instances.indexOf(this);
  13765. if (index >= 0) {
  13766. Engine.Instances.splice(index, 1);
  13767. }
  13768. this._workingCanvas = null;
  13769. this._workingContext = null;
  13770. this._currentBufferPointers = [];
  13771. this._renderingCanvas = null;
  13772. this._currentProgram = null;
  13773. this.onResizeObservable.clear();
  13774. this.onCanvasBlurObservable.clear();
  13775. this.onCanvasFocusObservable.clear();
  13776. this.onCanvasPointerOutObservable.clear();
  13777. this.onBeginFrameObservable.clear();
  13778. this.onEndFrameObservable.clear();
  13779. BABYLON.Effect.ResetCache();
  13780. // Abort active requests
  13781. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13782. var request = _a[_i];
  13783. request.abort();
  13784. }
  13785. };
  13786. // Loading screen
  13787. Engine.prototype.displayLoadingUI = function () {
  13788. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13789. return;
  13790. }
  13791. var loadingScreen = this.loadingScreen;
  13792. if (loadingScreen) {
  13793. loadingScreen.displayLoadingUI();
  13794. }
  13795. };
  13796. Engine.prototype.hideLoadingUI = function () {
  13797. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13798. return;
  13799. }
  13800. var loadingScreen = this.loadingScreen;
  13801. if (loadingScreen) {
  13802. loadingScreen.hideLoadingUI();
  13803. }
  13804. };
  13805. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13806. get: function () {
  13807. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13808. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13809. return this._loadingScreen;
  13810. },
  13811. set: function (loadingScreen) {
  13812. this._loadingScreen = loadingScreen;
  13813. },
  13814. enumerable: true,
  13815. configurable: true
  13816. });
  13817. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13818. set: function (text) {
  13819. this.loadingScreen.loadingUIText = text;
  13820. },
  13821. enumerable: true,
  13822. configurable: true
  13823. });
  13824. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13825. set: function (color) {
  13826. this.loadingScreen.loadingUIBackgroundColor = color;
  13827. },
  13828. enumerable: true,
  13829. configurable: true
  13830. });
  13831. Engine.prototype.attachContextLostEvent = function (callback) {
  13832. if (this._renderingCanvas) {
  13833. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13834. }
  13835. };
  13836. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13837. if (this._renderingCanvas) {
  13838. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13839. }
  13840. };
  13841. Engine.prototype.getVertexShaderSource = function (program) {
  13842. var shaders = this._gl.getAttachedShaders(program);
  13843. if (!shaders) {
  13844. return null;
  13845. }
  13846. return this._gl.getShaderSource(shaders[0]);
  13847. };
  13848. Engine.prototype.getFragmentShaderSource = function (program) {
  13849. var shaders = this._gl.getAttachedShaders(program);
  13850. if (!shaders) {
  13851. return null;
  13852. }
  13853. return this._gl.getShaderSource(shaders[1]);
  13854. };
  13855. Engine.prototype.getError = function () {
  13856. return this._gl.getError();
  13857. };
  13858. // FPS
  13859. Engine.prototype.getFps = function () {
  13860. return this._fps;
  13861. };
  13862. Engine.prototype.getDeltaTime = function () {
  13863. return this._deltaTime;
  13864. };
  13865. Engine.prototype._measureFps = function () {
  13866. this._performanceMonitor.sampleFrame();
  13867. this._fps = this._performanceMonitor.averageFPS;
  13868. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13869. };
  13870. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13871. if (faceIndex === void 0) { faceIndex = -1; }
  13872. var gl = this._gl;
  13873. if (!this._dummyFramebuffer) {
  13874. var dummy = gl.createFramebuffer();
  13875. if (!dummy) {
  13876. throw new Error("Unable to create dummy framebuffer");
  13877. }
  13878. this._dummyFramebuffer = dummy;
  13879. }
  13880. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13881. if (faceIndex > -1) {
  13882. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13883. }
  13884. else {
  13885. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13886. }
  13887. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13888. var buffer;
  13889. switch (readType) {
  13890. case gl.UNSIGNED_BYTE:
  13891. buffer = new Uint8Array(4 * width * height);
  13892. readType = gl.UNSIGNED_BYTE;
  13893. break;
  13894. default:
  13895. buffer = new Float32Array(4 * width * height);
  13896. readType = gl.FLOAT;
  13897. break;
  13898. }
  13899. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13900. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13901. return buffer;
  13902. };
  13903. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13904. if (this._webGLVersion > 1) {
  13905. return this._caps.colorBufferFloat;
  13906. }
  13907. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13908. };
  13909. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13910. if (this._webGLVersion > 1) {
  13911. return this._caps.colorBufferFloat;
  13912. }
  13913. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13914. };
  13915. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13916. Engine.prototype._canRenderToFramebuffer = function (type) {
  13917. var gl = this._gl;
  13918. //clear existing errors
  13919. while (gl.getError() !== gl.NO_ERROR) { }
  13920. var successful = true;
  13921. var texture = gl.createTexture();
  13922. gl.bindTexture(gl.TEXTURE_2D, texture);
  13923. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13924. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13925. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13926. var fb = gl.createFramebuffer();
  13927. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13928. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13929. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13930. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13931. successful = successful && (gl.getError() === gl.NO_ERROR);
  13932. //try render by clearing frame buffer's color buffer
  13933. if (successful) {
  13934. gl.clear(gl.COLOR_BUFFER_BIT);
  13935. successful = successful && (gl.getError() === gl.NO_ERROR);
  13936. }
  13937. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13938. if (successful) {
  13939. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13940. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13941. var readFormat = gl.RGBA;
  13942. var readType = gl.UNSIGNED_BYTE;
  13943. var buffer = new Uint8Array(4);
  13944. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13945. successful = successful && (gl.getError() === gl.NO_ERROR);
  13946. }
  13947. //clean up
  13948. gl.deleteTexture(texture);
  13949. gl.deleteFramebuffer(fb);
  13950. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13951. //clear accumulated errors
  13952. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13953. return successful;
  13954. };
  13955. Engine.prototype._getWebGLTextureType = function (type) {
  13956. if (type === Engine.TEXTURETYPE_FLOAT) {
  13957. return this._gl.FLOAT;
  13958. }
  13959. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13960. // Add Half Float Constant.
  13961. return this._gl.HALF_FLOAT_OES;
  13962. }
  13963. return this._gl.UNSIGNED_BYTE;
  13964. };
  13965. ;
  13966. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13967. if (this._webGLVersion === 1) {
  13968. return this._gl.RGBA;
  13969. }
  13970. if (type === Engine.TEXTURETYPE_FLOAT) {
  13971. return this._gl.RGBA32F;
  13972. }
  13973. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13974. return this._gl.RGBA16F;
  13975. }
  13976. return this._gl.RGBA;
  13977. };
  13978. ;
  13979. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13980. if (type === Engine.TEXTURETYPE_FLOAT) {
  13981. return this._gl.RGBA32F;
  13982. }
  13983. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13984. return this._gl.RGBA16F;
  13985. }
  13986. return this._gl.RGBA8;
  13987. };
  13988. ;
  13989. Engine.prototype.createQuery = function () {
  13990. return this._gl.createQuery();
  13991. };
  13992. Engine.prototype.deleteQuery = function (query) {
  13993. this._gl.deleteQuery(query);
  13994. return this;
  13995. };
  13996. Engine.prototype.isQueryResultAvailable = function (query) {
  13997. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13998. };
  13999. Engine.prototype.getQueryResult = function (query) {
  14000. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14001. };
  14002. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14003. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14004. this._gl.beginQuery(glAlgorithm, query);
  14005. return this;
  14006. };
  14007. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14008. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14009. this._gl.endQuery(glAlgorithm);
  14010. return this;
  14011. };
  14012. /* Time queries */
  14013. Engine.prototype._createTimeQuery = function () {
  14014. var timerQuery = this._caps.timerQuery;
  14015. if (timerQuery.createQueryEXT) {
  14016. return timerQuery.createQueryEXT();
  14017. }
  14018. return this.createQuery();
  14019. };
  14020. Engine.prototype._deleteTimeQuery = function (query) {
  14021. var timerQuery = this._caps.timerQuery;
  14022. if (timerQuery.deleteQueryEXT) {
  14023. timerQuery.deleteQueryEXT(query);
  14024. return;
  14025. }
  14026. this.deleteQuery(query);
  14027. };
  14028. Engine.prototype._getTimeQueryResult = function (query) {
  14029. var timerQuery = this._caps.timerQuery;
  14030. if (timerQuery.getQueryObjectEXT) {
  14031. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14032. }
  14033. return this.getQueryResult(query);
  14034. };
  14035. Engine.prototype._getTimeQueryAvailability = function (query) {
  14036. var timerQuery = this._caps.timerQuery;
  14037. if (timerQuery.getQueryObjectEXT) {
  14038. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14039. }
  14040. return this.isQueryResultAvailable(query);
  14041. };
  14042. Engine.prototype.startTimeQuery = function () {
  14043. var timerQuery = this._caps.timerQuery;
  14044. if (!timerQuery) {
  14045. return null;
  14046. }
  14047. var token = new BABYLON._TimeToken();
  14048. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14049. if (this._caps.canUseTimestampForTimerQuery) {
  14050. token._startTimeQuery = this._createTimeQuery();
  14051. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14052. }
  14053. else {
  14054. if (this._currentNonTimestampToken) {
  14055. return this._currentNonTimestampToken;
  14056. }
  14057. token._timeElapsedQuery = this._createTimeQuery();
  14058. if (timerQuery.beginQueryEXT) {
  14059. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14060. }
  14061. else {
  14062. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14063. }
  14064. this._currentNonTimestampToken = token;
  14065. }
  14066. return token;
  14067. };
  14068. Engine.prototype.endTimeQuery = function (token) {
  14069. var timerQuery = this._caps.timerQuery;
  14070. if (!timerQuery || !token) {
  14071. return -1;
  14072. }
  14073. if (this._caps.canUseTimestampForTimerQuery) {
  14074. if (!token._startTimeQuery) {
  14075. return -1;
  14076. }
  14077. if (!token._endTimeQuery) {
  14078. token._endTimeQuery = this._createTimeQuery();
  14079. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14080. }
  14081. }
  14082. else if (!token._timeElapsedQueryEnded) {
  14083. if (!token._timeElapsedQuery) {
  14084. return -1;
  14085. }
  14086. if (timerQuery.endQueryEXT) {
  14087. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14088. }
  14089. else {
  14090. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14091. }
  14092. token._timeElapsedQueryEnded = true;
  14093. }
  14094. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14095. var available = false;
  14096. if (token._endTimeQuery) {
  14097. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14098. }
  14099. else if (token._timeElapsedQuery) {
  14100. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14101. }
  14102. if (available && !disjoint) {
  14103. var result = 0;
  14104. if (this._caps.canUseTimestampForTimerQuery) {
  14105. if (!token._startTimeQuery || !token._endTimeQuery) {
  14106. return -1;
  14107. }
  14108. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14109. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14110. result = timeEnd - timeStart;
  14111. this._deleteTimeQuery(token._startTimeQuery);
  14112. this._deleteTimeQuery(token._endTimeQuery);
  14113. token._startTimeQuery = null;
  14114. token._endTimeQuery = null;
  14115. }
  14116. else {
  14117. if (!token._timeElapsedQuery) {
  14118. return -1;
  14119. }
  14120. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14121. this._deleteTimeQuery(token._timeElapsedQuery);
  14122. token._timeElapsedQuery = null;
  14123. token._timeElapsedQueryEnded = false;
  14124. this._currentNonTimestampToken = null;
  14125. }
  14126. return result;
  14127. }
  14128. return -1;
  14129. };
  14130. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14131. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14132. };
  14133. // Transform feedback
  14134. Engine.prototype.createTransformFeedback = function () {
  14135. return this._gl.createTransformFeedback();
  14136. };
  14137. Engine.prototype.deleteTransformFeedback = function (value) {
  14138. this._gl.deleteTransformFeedback(value);
  14139. };
  14140. Engine.prototype.bindTransformFeedback = function (value) {
  14141. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14142. };
  14143. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14144. if (usePoints === void 0) { usePoints = true; }
  14145. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14146. };
  14147. Engine.prototype.endTransformFeedback = function () {
  14148. this._gl.endTransformFeedback();
  14149. };
  14150. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14151. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14152. };
  14153. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14154. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14155. };
  14156. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14157. var _this = this;
  14158. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14159. this._activeRequests.push(request);
  14160. request.onCompleteObservable.add(function (request) {
  14161. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14162. });
  14163. return request;
  14164. };
  14165. /** @ignore */
  14166. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14167. var _this = this;
  14168. return new Promise(function (resolve, reject) {
  14169. _this._loadFile(url, function (data) {
  14170. resolve(data);
  14171. }, undefined, database, useArrayBuffer, function (request, exception) {
  14172. reject(exception);
  14173. });
  14174. });
  14175. };
  14176. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14177. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14178. var onload = function (data) {
  14179. loadedFiles[index] = data;
  14180. loadedFiles._internalCount++;
  14181. if (loadedFiles._internalCount === 6) {
  14182. onfinish(loadedFiles);
  14183. }
  14184. };
  14185. var onerror = function (request, exception) {
  14186. if (onErrorCallBack && request) {
  14187. onErrorCallBack(request.status + " " + request.statusText, exception);
  14188. }
  14189. };
  14190. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14191. };
  14192. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14193. if (onError === void 0) { onError = null; }
  14194. var loadedFiles = [];
  14195. loadedFiles._internalCount = 0;
  14196. for (var index = 0; index < 6; index++) {
  14197. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14198. }
  14199. };
  14200. // Statics
  14201. Engine.isSupported = function () {
  14202. try {
  14203. var tempcanvas = document.createElement("canvas");
  14204. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14205. return gl != null && !!window.WebGLRenderingContext;
  14206. }
  14207. catch (e) {
  14208. return false;
  14209. }
  14210. };
  14211. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14212. Engine.ExceptionList = [
  14213. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14214. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14215. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14216. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14217. ];
  14218. Engine.Instances = new Array();
  14219. // Const statics
  14220. Engine._ALPHA_DISABLE = 0;
  14221. Engine._ALPHA_ADD = 1;
  14222. Engine._ALPHA_COMBINE = 2;
  14223. Engine._ALPHA_SUBTRACT = 3;
  14224. Engine._ALPHA_MULTIPLY = 4;
  14225. Engine._ALPHA_MAXIMIZED = 5;
  14226. Engine._ALPHA_ONEONE = 6;
  14227. Engine._ALPHA_PREMULTIPLIED = 7;
  14228. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14229. Engine._ALPHA_INTERPOLATE = 9;
  14230. Engine._ALPHA_SCREENMODE = 10;
  14231. Engine._DELAYLOADSTATE_NONE = 0;
  14232. Engine._DELAYLOADSTATE_LOADED = 1;
  14233. Engine._DELAYLOADSTATE_LOADING = 2;
  14234. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14235. Engine._TEXTUREFORMAT_ALPHA = 0;
  14236. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14237. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14238. Engine._TEXTUREFORMAT_RGB = 4;
  14239. Engine._TEXTUREFORMAT_RGBA = 5;
  14240. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14241. Engine._TEXTURETYPE_FLOAT = 1;
  14242. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14243. // Depht or Stencil test Constants.
  14244. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14245. 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.
  14246. 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.
  14247. 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.
  14248. 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.
  14249. 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.
  14250. 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.
  14251. 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.
  14252. // Stencil Actions Constants.
  14253. Engine._KEEP = 0x1E00;
  14254. Engine._REPLACE = 0x1E01;
  14255. Engine._INCR = 0x1E02;
  14256. Engine._DECR = 0x1E03;
  14257. Engine._INVERT = 0x150A;
  14258. Engine._INCR_WRAP = 0x8507;
  14259. Engine._DECR_WRAP = 0x8508;
  14260. // Texture rescaling mode
  14261. Engine._SCALEMODE_FLOOR = 1;
  14262. Engine._SCALEMODE_NEAREST = 2;
  14263. Engine._SCALEMODE_CEILING = 3;
  14264. // Updatable statics so stick with vars here
  14265. Engine.CollisionsEpsilon = 0.001;
  14266. Engine.CodeRepository = "src/";
  14267. Engine.ShadersRepository = "src/Shaders/";
  14268. return Engine;
  14269. }());
  14270. BABYLON.Engine = Engine;
  14271. })(BABYLON || (BABYLON = {}));
  14272. //# sourceMappingURL=babylon.engine.js.map
  14273. var BABYLON;
  14274. (function (BABYLON) {
  14275. /**
  14276. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14277. */
  14278. var Node = /** @class */ (function () {
  14279. /**
  14280. * @constructor
  14281. * @param {string} name - the name and id to be given to this node
  14282. * @param {BABYLON.Scene} the scene this node will be added to
  14283. */
  14284. function Node(name, scene) {
  14285. if (scene === void 0) { scene = null; }
  14286. this.state = "";
  14287. this.metadata = null;
  14288. this.doNotSerialize = false;
  14289. this.animations = new Array();
  14290. this._ranges = {};
  14291. this._isEnabled = true;
  14292. this._isReady = true;
  14293. this._currentRenderId = -1;
  14294. this._parentRenderId = -1;
  14295. /**
  14296. * An event triggered when the mesh is disposed.
  14297. * @type {BABYLON.Observable}
  14298. */
  14299. this.onDisposeObservable = new BABYLON.Observable();
  14300. // Behaviors
  14301. this._behaviors = new Array();
  14302. this.name = name;
  14303. this.id = name;
  14304. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14305. this.uniqueId = this._scene.getUniqueId();
  14306. this._initCache();
  14307. }
  14308. Object.defineProperty(Node.prototype, "parent", {
  14309. get: function () {
  14310. return this._parentNode;
  14311. },
  14312. set: function (parent) {
  14313. if (this._parentNode === parent) {
  14314. return;
  14315. }
  14316. // Remove self from list of children of parent
  14317. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14318. var index = this._parentNode._children.indexOf(this);
  14319. if (index !== -1) {
  14320. this._parentNode._children.splice(index, 1);
  14321. }
  14322. }
  14323. // Store new parent
  14324. this._parentNode = parent;
  14325. // Add as child to new parent
  14326. if (this._parentNode) {
  14327. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14328. this._parentNode._children = new Array();
  14329. }
  14330. this._parentNode._children.push(this);
  14331. }
  14332. },
  14333. enumerable: true,
  14334. configurable: true
  14335. });
  14336. Node.prototype.getClassName = function () {
  14337. return "Node";
  14338. };
  14339. Object.defineProperty(Node.prototype, "onDispose", {
  14340. set: function (callback) {
  14341. if (this._onDisposeObserver) {
  14342. this.onDisposeObservable.remove(this._onDisposeObserver);
  14343. }
  14344. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14345. },
  14346. enumerable: true,
  14347. configurable: true
  14348. });
  14349. Node.prototype.getScene = function () {
  14350. return this._scene;
  14351. };
  14352. Node.prototype.getEngine = function () {
  14353. return this._scene.getEngine();
  14354. };
  14355. Node.prototype.addBehavior = function (behavior) {
  14356. var _this = this;
  14357. var index = this._behaviors.indexOf(behavior);
  14358. if (index !== -1) {
  14359. return this;
  14360. }
  14361. behavior.init();
  14362. if (this._scene.isLoading) {
  14363. // We defer the attach when the scene will be loaded
  14364. var observer = this._scene.onDataLoadedObservable.add(function () {
  14365. behavior.attach(_this);
  14366. setTimeout(function () {
  14367. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  14368. _this._scene.onDataLoadedObservable.remove(observer);
  14369. }, 0);
  14370. });
  14371. }
  14372. else {
  14373. behavior.attach(this);
  14374. }
  14375. this._behaviors.push(behavior);
  14376. return this;
  14377. };
  14378. Node.prototype.removeBehavior = function (behavior) {
  14379. var index = this._behaviors.indexOf(behavior);
  14380. if (index === -1) {
  14381. return this;
  14382. }
  14383. this._behaviors[index].detach();
  14384. this._behaviors.splice(index, 1);
  14385. return this;
  14386. };
  14387. Object.defineProperty(Node.prototype, "behaviors", {
  14388. get: function () {
  14389. return this._behaviors;
  14390. },
  14391. enumerable: true,
  14392. configurable: true
  14393. });
  14394. Node.prototype.getBehaviorByName = function (name) {
  14395. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14396. var behavior = _a[_i];
  14397. if (behavior.name === name) {
  14398. return behavior;
  14399. }
  14400. }
  14401. return null;
  14402. };
  14403. // override it in derived class
  14404. Node.prototype.getWorldMatrix = function () {
  14405. return BABYLON.Matrix.Identity();
  14406. };
  14407. // override it in derived class if you add new variables to the cache
  14408. // and call the parent class method
  14409. Node.prototype._initCache = function () {
  14410. this._cache = {};
  14411. this._cache.parent = undefined;
  14412. };
  14413. Node.prototype.updateCache = function (force) {
  14414. if (!force && this.isSynchronized())
  14415. return;
  14416. this._cache.parent = this.parent;
  14417. this._updateCache();
  14418. };
  14419. // override it in derived class if you add new variables to the cache
  14420. // and call the parent class method if !ignoreParentClass
  14421. Node.prototype._updateCache = function (ignoreParentClass) {
  14422. };
  14423. // override it in derived class if you add new variables to the cache
  14424. Node.prototype._isSynchronized = function () {
  14425. return true;
  14426. };
  14427. Node.prototype._markSyncedWithParent = function () {
  14428. if (this.parent) {
  14429. this._parentRenderId = this.parent._currentRenderId;
  14430. }
  14431. };
  14432. Node.prototype.isSynchronizedWithParent = function () {
  14433. if (!this.parent) {
  14434. return true;
  14435. }
  14436. if (this._parentRenderId !== this.parent._currentRenderId) {
  14437. return false;
  14438. }
  14439. return this.parent.isSynchronized();
  14440. };
  14441. Node.prototype.isSynchronized = function (updateCache) {
  14442. var check = this.hasNewParent();
  14443. check = check || !this.isSynchronizedWithParent();
  14444. check = check || !this._isSynchronized();
  14445. if (updateCache)
  14446. this.updateCache(true);
  14447. return !check;
  14448. };
  14449. Node.prototype.hasNewParent = function (update) {
  14450. if (this._cache.parent === this.parent)
  14451. return false;
  14452. if (update)
  14453. this._cache.parent = this.parent;
  14454. return true;
  14455. };
  14456. /**
  14457. * Is this node ready to be used/rendered
  14458. * @return {boolean} is it ready
  14459. */
  14460. Node.prototype.isReady = function () {
  14461. return this._isReady;
  14462. };
  14463. /**
  14464. * Is this node enabled.
  14465. * 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.
  14466. * @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.
  14467. * @return {boolean} whether this node (and its parent) is enabled.
  14468. * @see setEnabled
  14469. */
  14470. Node.prototype.isEnabled = function (checkAncestors) {
  14471. if (checkAncestors === void 0) { checkAncestors = true; }
  14472. if (checkAncestors === false) {
  14473. return this._isEnabled;
  14474. }
  14475. if (this._isEnabled === false) {
  14476. return false;
  14477. }
  14478. if (this.parent !== undefined && this.parent !== null) {
  14479. return this.parent.isEnabled(checkAncestors);
  14480. }
  14481. return true;
  14482. };
  14483. /**
  14484. * Set the enabled state of this node.
  14485. * @param {boolean} value - the new enabled state
  14486. * @see isEnabled
  14487. */
  14488. Node.prototype.setEnabled = function (value) {
  14489. this._isEnabled = value;
  14490. };
  14491. /**
  14492. * Is this node a descendant of the given node.
  14493. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  14494. * @param {BABYLON.Node} ancestor - The parent node to inspect
  14495. * @see parent
  14496. */
  14497. Node.prototype.isDescendantOf = function (ancestor) {
  14498. if (this.parent) {
  14499. if (this.parent === ancestor) {
  14500. return true;
  14501. }
  14502. return this.parent.isDescendantOf(ancestor);
  14503. }
  14504. return false;
  14505. };
  14506. /**
  14507. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  14508. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  14509. * @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.
  14510. * @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.
  14511. */
  14512. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  14513. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  14514. if (!this._children) {
  14515. return;
  14516. }
  14517. for (var index = 0; index < this._children.length; index++) {
  14518. var item = this._children[index];
  14519. if (!predicate || predicate(item)) {
  14520. results.push(item);
  14521. }
  14522. if (!directDescendantsOnly) {
  14523. item._getDescendants(results, false, predicate);
  14524. }
  14525. }
  14526. };
  14527. /**
  14528. * Will return all nodes that have this node as ascendant.
  14529. * @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.
  14530. * @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.
  14531. * @return {BABYLON.Node[]} all children nodes of all types.
  14532. */
  14533. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  14534. var results = new Array();
  14535. this._getDescendants(results, directDescendantsOnly, predicate);
  14536. return results;
  14537. };
  14538. /**
  14539. * Get all child-meshes of this node.
  14540. */
  14541. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  14542. var results = [];
  14543. this._getDescendants(results, directDescendantsOnly, function (node) {
  14544. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  14545. });
  14546. return results;
  14547. };
  14548. /**
  14549. * Get all child-transformNodes of this node.
  14550. */
  14551. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  14552. var results = [];
  14553. this._getDescendants(results, directDescendantsOnly, function (node) {
  14554. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  14555. });
  14556. return results;
  14557. };
  14558. /**
  14559. * Get all direct children of this node.
  14560. */
  14561. Node.prototype.getChildren = function (predicate) {
  14562. return this.getDescendants(true, predicate);
  14563. };
  14564. Node.prototype._setReady = function (state) {
  14565. if (state === this._isReady) {
  14566. return;
  14567. }
  14568. if (!state) {
  14569. this._isReady = false;
  14570. return;
  14571. }
  14572. this._isReady = true;
  14573. if (this.onReady) {
  14574. this.onReady(this);
  14575. }
  14576. };
  14577. Node.prototype.getAnimationByName = function (name) {
  14578. for (var i = 0; i < this.animations.length; i++) {
  14579. var animation = this.animations[i];
  14580. if (animation.name === name) {
  14581. return animation;
  14582. }
  14583. }
  14584. return null;
  14585. };
  14586. Node.prototype.createAnimationRange = function (name, from, to) {
  14587. // check name not already in use
  14588. if (!this._ranges[name]) {
  14589. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14590. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14591. if (this.animations[i]) {
  14592. this.animations[i].createRange(name, from, to);
  14593. }
  14594. }
  14595. }
  14596. };
  14597. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14598. if (deleteFrames === void 0) { deleteFrames = true; }
  14599. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14600. if (this.animations[i]) {
  14601. this.animations[i].deleteRange(name, deleteFrames);
  14602. }
  14603. }
  14604. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14605. };
  14606. Node.prototype.getAnimationRange = function (name) {
  14607. return this._ranges[name];
  14608. };
  14609. /**
  14610. * Will start the animation sequence
  14611. * @param name defines the range frames for animation sequence
  14612. * @param loop defines if the animation should loop (false by default)
  14613. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  14614. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  14615. * @returns the {BABYLON.Animatable} object created for this animation. If range does not exist, it will return null
  14616. */
  14617. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14618. var range = this.getAnimationRange(name);
  14619. if (!range) {
  14620. return null;
  14621. }
  14622. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14623. };
  14624. Node.prototype.serializeAnimationRanges = function () {
  14625. var serializationRanges = [];
  14626. for (var name in this._ranges) {
  14627. var localRange = this._ranges[name];
  14628. if (!localRange) {
  14629. continue;
  14630. }
  14631. var range = {};
  14632. range.name = name;
  14633. range.from = localRange.from;
  14634. range.to = localRange.to;
  14635. serializationRanges.push(range);
  14636. }
  14637. return serializationRanges;
  14638. };
  14639. // override it in derived class
  14640. Node.prototype.computeWorldMatrix = function (force) {
  14641. return BABYLON.Matrix.Identity();
  14642. };
  14643. Node.prototype.dispose = function () {
  14644. this.parent = null;
  14645. // Callback
  14646. this.onDisposeObservable.notifyObservers(this);
  14647. this.onDisposeObservable.clear();
  14648. // Behaviors
  14649. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14650. var behavior = _a[_i];
  14651. behavior.detach();
  14652. }
  14653. this._behaviors = [];
  14654. };
  14655. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14656. if (parsedNode.ranges) {
  14657. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14658. var data = parsedNode.ranges[index];
  14659. node.createAnimationRange(data.name, data.from, data.to);
  14660. }
  14661. }
  14662. };
  14663. __decorate([
  14664. BABYLON.serialize()
  14665. ], Node.prototype, "name", void 0);
  14666. __decorate([
  14667. BABYLON.serialize()
  14668. ], Node.prototype, "id", void 0);
  14669. __decorate([
  14670. BABYLON.serialize()
  14671. ], Node.prototype, "uniqueId", void 0);
  14672. __decorate([
  14673. BABYLON.serialize()
  14674. ], Node.prototype, "state", void 0);
  14675. __decorate([
  14676. BABYLON.serialize()
  14677. ], Node.prototype, "metadata", void 0);
  14678. return Node;
  14679. }());
  14680. BABYLON.Node = Node;
  14681. })(BABYLON || (BABYLON = {}));
  14682. //# sourceMappingURL=babylon.node.js.map
  14683. var BABYLON;
  14684. (function (BABYLON) {
  14685. var BoundingSphere = /** @class */ (function () {
  14686. function BoundingSphere(minimum, maximum) {
  14687. this.minimum = minimum;
  14688. this.maximum = maximum;
  14689. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14690. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14691. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14692. this.radius = distance * 0.5;
  14693. this.centerWorld = BABYLON.Vector3.Zero();
  14694. this._update(BABYLON.Matrix.Identity());
  14695. }
  14696. // Methods
  14697. BoundingSphere.prototype._update = function (world) {
  14698. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14699. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14700. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14701. };
  14702. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14703. for (var i = 0; i < 6; i++) {
  14704. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14705. return false;
  14706. }
  14707. return true;
  14708. };
  14709. BoundingSphere.prototype.intersectsPoint = function (point) {
  14710. var x = this.centerWorld.x - point.x;
  14711. var y = this.centerWorld.y - point.y;
  14712. var z = this.centerWorld.z - point.z;
  14713. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14714. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14715. return false;
  14716. return true;
  14717. };
  14718. // Statics
  14719. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14720. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14721. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14722. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14723. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14724. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14725. return false;
  14726. return true;
  14727. };
  14728. return BoundingSphere;
  14729. }());
  14730. BABYLON.BoundingSphere = BoundingSphere;
  14731. })(BABYLON || (BABYLON = {}));
  14732. //# sourceMappingURL=babylon.boundingSphere.js.map
  14733. var BABYLON;
  14734. (function (BABYLON) {
  14735. var BoundingBox = /** @class */ (function () {
  14736. function BoundingBox(minimum, maximum) {
  14737. this.minimum = minimum;
  14738. this.maximum = maximum;
  14739. this.vectors = new Array();
  14740. this.vectorsWorld = new Array();
  14741. // Bounding vectors
  14742. this.vectors.push(this.minimum.clone());
  14743. this.vectors.push(this.maximum.clone());
  14744. this.vectors.push(this.minimum.clone());
  14745. this.vectors[2].x = this.maximum.x;
  14746. this.vectors.push(this.minimum.clone());
  14747. this.vectors[3].y = this.maximum.y;
  14748. this.vectors.push(this.minimum.clone());
  14749. this.vectors[4].z = this.maximum.z;
  14750. this.vectors.push(this.maximum.clone());
  14751. this.vectors[5].z = this.minimum.z;
  14752. this.vectors.push(this.maximum.clone());
  14753. this.vectors[6].x = this.minimum.x;
  14754. this.vectors.push(this.maximum.clone());
  14755. this.vectors[7].y = this.minimum.y;
  14756. // OBB
  14757. this.center = this.maximum.add(this.minimum).scale(0.5);
  14758. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14759. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14760. // World
  14761. for (var index = 0; index < this.vectors.length; index++) {
  14762. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14763. }
  14764. this.minimumWorld = BABYLON.Vector3.Zero();
  14765. this.maximumWorld = BABYLON.Vector3.Zero();
  14766. this.centerWorld = BABYLON.Vector3.Zero();
  14767. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14768. this._update(BABYLON.Matrix.Identity());
  14769. }
  14770. // Methods
  14771. BoundingBox.prototype.getWorldMatrix = function () {
  14772. return this._worldMatrix;
  14773. };
  14774. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14775. this._worldMatrix.copyFrom(matrix);
  14776. return this;
  14777. };
  14778. BoundingBox.prototype._update = function (world) {
  14779. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14780. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14781. for (var index = 0; index < this.vectors.length; index++) {
  14782. var v = this.vectorsWorld[index];
  14783. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14784. if (v.x < this.minimumWorld.x)
  14785. this.minimumWorld.x = v.x;
  14786. if (v.y < this.minimumWorld.y)
  14787. this.minimumWorld.y = v.y;
  14788. if (v.z < this.minimumWorld.z)
  14789. this.minimumWorld.z = v.z;
  14790. if (v.x > this.maximumWorld.x)
  14791. this.maximumWorld.x = v.x;
  14792. if (v.y > this.maximumWorld.y)
  14793. this.maximumWorld.y = v.y;
  14794. if (v.z > this.maximumWorld.z)
  14795. this.maximumWorld.z = v.z;
  14796. }
  14797. // Extend
  14798. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14799. this.extendSizeWorld.scaleInPlace(0.5);
  14800. // OBB
  14801. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14802. this.centerWorld.scaleInPlace(0.5);
  14803. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14804. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14805. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14806. this._worldMatrix = world;
  14807. };
  14808. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14809. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14810. };
  14811. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14812. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14813. };
  14814. BoundingBox.prototype.intersectsPoint = function (point) {
  14815. var delta = -BABYLON.Epsilon;
  14816. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14817. return false;
  14818. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14819. return false;
  14820. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14821. return false;
  14822. return true;
  14823. };
  14824. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14825. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14826. };
  14827. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14828. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14829. return false;
  14830. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14831. return false;
  14832. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14833. return false;
  14834. return true;
  14835. };
  14836. // Statics
  14837. BoundingBox.Intersects = function (box0, box1) {
  14838. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14839. return false;
  14840. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14841. return false;
  14842. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14843. return false;
  14844. return true;
  14845. };
  14846. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14847. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14848. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14849. return (num <= (sphereRadius * sphereRadius));
  14850. };
  14851. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14852. for (var p = 0; p < 6; p++) {
  14853. for (var i = 0; i < 8; i++) {
  14854. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14855. return false;
  14856. }
  14857. }
  14858. }
  14859. return true;
  14860. };
  14861. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14862. for (var p = 0; p < 6; p++) {
  14863. var inCount = 8;
  14864. for (var i = 0; i < 8; i++) {
  14865. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14866. --inCount;
  14867. }
  14868. else {
  14869. break;
  14870. }
  14871. }
  14872. if (inCount === 0)
  14873. return false;
  14874. }
  14875. return true;
  14876. };
  14877. return BoundingBox;
  14878. }());
  14879. BABYLON.BoundingBox = BoundingBox;
  14880. })(BABYLON || (BABYLON = {}));
  14881. //# sourceMappingURL=babylon.boundingBox.js.map
  14882. var BABYLON;
  14883. (function (BABYLON) {
  14884. var computeBoxExtents = function (axis, box) {
  14885. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14886. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14887. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14888. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14889. var r = r0 + r1 + r2;
  14890. return {
  14891. min: p - r,
  14892. max: p + r
  14893. };
  14894. };
  14895. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14896. var axisOverlap = function (axis, box0, box1) {
  14897. var result0 = computeBoxExtents(axis, box0);
  14898. var result1 = computeBoxExtents(axis, box1);
  14899. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14900. };
  14901. var BoundingInfo = /** @class */ (function () {
  14902. function BoundingInfo(minimum, maximum) {
  14903. this.minimum = minimum;
  14904. this.maximum = maximum;
  14905. this._isLocked = false;
  14906. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14907. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14908. }
  14909. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14910. get: function () {
  14911. return this._isLocked;
  14912. },
  14913. set: function (value) {
  14914. this._isLocked = value;
  14915. },
  14916. enumerable: true,
  14917. configurable: true
  14918. });
  14919. // Methods
  14920. BoundingInfo.prototype.update = function (world) {
  14921. if (this._isLocked) {
  14922. return;
  14923. }
  14924. this.boundingBox._update(world);
  14925. this.boundingSphere._update(world);
  14926. };
  14927. /**
  14928. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14929. * @param center New center of the bounding info
  14930. * @param extend New extend of the bounding info
  14931. */
  14932. BoundingInfo.prototype.centerOn = function (center, extend) {
  14933. this.minimum = center.subtract(extend);
  14934. this.maximum = center.add(extend);
  14935. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14936. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14937. return this;
  14938. };
  14939. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14940. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14941. return false;
  14942. return this.boundingBox.isInFrustum(frustumPlanes);
  14943. };
  14944. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14945. /**
  14946. * Gets the world distance between the min and max points of the bounding box
  14947. */
  14948. get: function () {
  14949. var boundingBox = this.boundingBox;
  14950. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14951. return size.length();
  14952. },
  14953. enumerable: true,
  14954. configurable: true
  14955. });
  14956. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14957. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14958. };
  14959. BoundingInfo.prototype._checkCollision = function (collider) {
  14960. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14961. };
  14962. BoundingInfo.prototype.intersectsPoint = function (point) {
  14963. if (!this.boundingSphere.centerWorld) {
  14964. return false;
  14965. }
  14966. if (!this.boundingSphere.intersectsPoint(point)) {
  14967. return false;
  14968. }
  14969. if (!this.boundingBox.intersectsPoint(point)) {
  14970. return false;
  14971. }
  14972. return true;
  14973. };
  14974. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14975. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14976. return false;
  14977. }
  14978. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14979. return false;
  14980. }
  14981. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14982. return false;
  14983. }
  14984. if (!precise) {
  14985. return true;
  14986. }
  14987. var box0 = this.boundingBox;
  14988. var box1 = boundingInfo.boundingBox;
  14989. if (!axisOverlap(box0.directions[0], box0, box1))
  14990. return false;
  14991. if (!axisOverlap(box0.directions[1], box0, box1))
  14992. return false;
  14993. if (!axisOverlap(box0.directions[2], box0, box1))
  14994. return false;
  14995. if (!axisOverlap(box1.directions[0], box0, box1))
  14996. return false;
  14997. if (!axisOverlap(box1.directions[1], box0, box1))
  14998. return false;
  14999. if (!axisOverlap(box1.directions[2], box0, box1))
  15000. return false;
  15001. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15002. return false;
  15003. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15004. return false;
  15005. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15006. return false;
  15007. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15008. return false;
  15009. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15010. return false;
  15011. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15012. return false;
  15013. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15014. return false;
  15015. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15016. return false;
  15017. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15018. return false;
  15019. return true;
  15020. };
  15021. return BoundingInfo;
  15022. }());
  15023. BABYLON.BoundingInfo = BoundingInfo;
  15024. })(BABYLON || (BABYLON = {}));
  15025. //# sourceMappingURL=babylon.boundingInfo.js.map
  15026. var BABYLON;
  15027. (function (BABYLON) {
  15028. var TransformNode = /** @class */ (function (_super) {
  15029. __extends(TransformNode, _super);
  15030. function TransformNode(name, scene, isPure) {
  15031. if (scene === void 0) { scene = null; }
  15032. if (isPure === void 0) { isPure = true; }
  15033. var _this = _super.call(this, name, scene) || this;
  15034. // Properties
  15035. _this._rotation = BABYLON.Vector3.Zero();
  15036. _this._scaling = BABYLON.Vector3.One();
  15037. _this._isDirty = false;
  15038. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15039. _this.scalingDeterminant = 1;
  15040. _this.infiniteDistance = false;
  15041. _this.position = BABYLON.Vector3.Zero();
  15042. _this._localWorld = BABYLON.Matrix.Zero();
  15043. _this._worldMatrix = BABYLON.Matrix.Zero();
  15044. _this._worldMatrixDeterminant = 0;
  15045. _this._absolutePosition = BABYLON.Vector3.Zero();
  15046. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15047. _this._postMultiplyPivotMatrix = false;
  15048. _this._isWorldMatrixFrozen = false;
  15049. /**
  15050. * An event triggered after the world matrix is updated
  15051. * @type {BABYLON.Observable}
  15052. */
  15053. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15054. _this._nonUniformScaling = false;
  15055. if (isPure) {
  15056. _this.getScene().addTransformNode(_this);
  15057. }
  15058. return _this;
  15059. }
  15060. Object.defineProperty(TransformNode.prototype, "rotation", {
  15061. /**
  15062. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15063. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15064. * Default : (0.0, 0.0, 0.0)
  15065. */
  15066. get: function () {
  15067. return this._rotation;
  15068. },
  15069. set: function (newRotation) {
  15070. this._rotation = newRotation;
  15071. },
  15072. enumerable: true,
  15073. configurable: true
  15074. });
  15075. Object.defineProperty(TransformNode.prototype, "scaling", {
  15076. /**
  15077. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15078. * Default : (1.0, 1.0, 1.0)
  15079. */
  15080. get: function () {
  15081. return this._scaling;
  15082. },
  15083. /**
  15084. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15085. * Default : (1.0, 1.0, 1.0)
  15086. */
  15087. set: function (newScaling) {
  15088. this._scaling = newScaling;
  15089. },
  15090. enumerable: true,
  15091. configurable: true
  15092. });
  15093. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15094. /**
  15095. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15096. * It's null by default.
  15097. * 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)
  15098. */
  15099. get: function () {
  15100. return this._rotationQuaternion;
  15101. },
  15102. set: function (quaternion) {
  15103. this._rotationQuaternion = quaternion;
  15104. //reset the rotation vector.
  15105. if (quaternion && this.rotation.length()) {
  15106. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15107. }
  15108. },
  15109. enumerable: true,
  15110. configurable: true
  15111. });
  15112. /**
  15113. * Returns the latest update of the World matrix
  15114. * Returns a Matrix.
  15115. */
  15116. TransformNode.prototype.getWorldMatrix = function () {
  15117. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15118. this.computeWorldMatrix();
  15119. }
  15120. return this._worldMatrix;
  15121. };
  15122. /**
  15123. * Returns the latest update of the World matrix determinant.
  15124. */
  15125. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15126. return this._worldMatrixDeterminant;
  15127. };
  15128. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15129. /**
  15130. * Returns directly the latest state of the mesh World matrix.
  15131. * A Matrix is returned.
  15132. */
  15133. get: function () {
  15134. return this._worldMatrix;
  15135. },
  15136. enumerable: true,
  15137. configurable: true
  15138. });
  15139. /**
  15140. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15141. * Returns the AbstractMesh.
  15142. */
  15143. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15144. this._poseMatrix.copyFrom(matrix);
  15145. return this;
  15146. };
  15147. /**
  15148. * Returns the mesh Pose matrix.
  15149. * Returned object : Matrix
  15150. */
  15151. TransformNode.prototype.getPoseMatrix = function () {
  15152. return this._poseMatrix;
  15153. };
  15154. TransformNode.prototype._isSynchronized = function () {
  15155. if (this._isDirty) {
  15156. return false;
  15157. }
  15158. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15159. return false;
  15160. if (this._cache.pivotMatrixUpdated) {
  15161. return false;
  15162. }
  15163. if (this.infiniteDistance) {
  15164. return false;
  15165. }
  15166. if (!this._cache.position.equals(this.position))
  15167. return false;
  15168. if (this.rotationQuaternion) {
  15169. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15170. return false;
  15171. }
  15172. if (!this._cache.rotation.equals(this.rotation))
  15173. return false;
  15174. if (!this._cache.scaling.equals(this.scaling))
  15175. return false;
  15176. return true;
  15177. };
  15178. TransformNode.prototype._initCache = function () {
  15179. _super.prototype._initCache.call(this);
  15180. this._cache.localMatrixUpdated = false;
  15181. this._cache.position = BABYLON.Vector3.Zero();
  15182. this._cache.scaling = BABYLON.Vector3.Zero();
  15183. this._cache.rotation = BABYLON.Vector3.Zero();
  15184. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15185. this._cache.billboardMode = -1;
  15186. };
  15187. TransformNode.prototype.markAsDirty = function (property) {
  15188. if (property === "rotation") {
  15189. this.rotationQuaternion = null;
  15190. }
  15191. this._currentRenderId = Number.MAX_VALUE;
  15192. this._isDirty = true;
  15193. return this;
  15194. };
  15195. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15196. /**
  15197. * Returns the current mesh absolute position.
  15198. * Retuns a Vector3.
  15199. */
  15200. get: function () {
  15201. return this._absolutePosition;
  15202. },
  15203. enumerable: true,
  15204. configurable: true
  15205. });
  15206. /**
  15207. * Sets a new matrix to apply before all other transformation
  15208. * @param matrix defines the transform matrix
  15209. * @returns the current TransformNode
  15210. */
  15211. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  15212. return this.setPivotMatrix(matrix, false);
  15213. };
  15214. /**
  15215. * Sets a new pivot matrix to the current node
  15216. * @param matrix defines the new pivot matrix to use
  15217. * @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
  15218. * @returns the current TransformNode
  15219. */
  15220. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15221. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  15222. this._pivotMatrix = matrix.clone();
  15223. this._cache.pivotMatrixUpdated = true;
  15224. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15225. if (this._postMultiplyPivotMatrix) {
  15226. if (!this._pivotMatrixInverse) {
  15227. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15228. }
  15229. else {
  15230. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  15231. }
  15232. }
  15233. return this;
  15234. };
  15235. /**
  15236. * Returns the mesh pivot matrix.
  15237. * Default : Identity.
  15238. * A Matrix is returned.
  15239. */
  15240. TransformNode.prototype.getPivotMatrix = function () {
  15241. return this._pivotMatrix;
  15242. };
  15243. /**
  15244. * Prevents the World matrix to be computed any longer.
  15245. * Returns the AbstractMesh.
  15246. */
  15247. TransformNode.prototype.freezeWorldMatrix = function () {
  15248. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15249. this.computeWorldMatrix(true);
  15250. this._isWorldMatrixFrozen = true;
  15251. return this;
  15252. };
  15253. /**
  15254. * Allows back the World matrix computation.
  15255. * Returns the AbstractMesh.
  15256. */
  15257. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15258. this._isWorldMatrixFrozen = false;
  15259. this.computeWorldMatrix(true);
  15260. return this;
  15261. };
  15262. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15263. /**
  15264. * True if the World matrix has been frozen.
  15265. * Returns a boolean.
  15266. */
  15267. get: function () {
  15268. return this._isWorldMatrixFrozen;
  15269. },
  15270. enumerable: true,
  15271. configurable: true
  15272. });
  15273. /**
  15274. * Retuns the mesh absolute position in the World.
  15275. * Returns a Vector3.
  15276. */
  15277. TransformNode.prototype.getAbsolutePosition = function () {
  15278. this.computeWorldMatrix();
  15279. return this._absolutePosition;
  15280. };
  15281. /**
  15282. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15283. * Returns the AbstractMesh.
  15284. */
  15285. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15286. if (!absolutePosition) {
  15287. return this;
  15288. }
  15289. var absolutePositionX;
  15290. var absolutePositionY;
  15291. var absolutePositionZ;
  15292. if (absolutePosition.x === undefined) {
  15293. if (arguments.length < 3) {
  15294. return this;
  15295. }
  15296. absolutePositionX = arguments[0];
  15297. absolutePositionY = arguments[1];
  15298. absolutePositionZ = arguments[2];
  15299. }
  15300. else {
  15301. absolutePositionX = absolutePosition.x;
  15302. absolutePositionY = absolutePosition.y;
  15303. absolutePositionZ = absolutePosition.z;
  15304. }
  15305. if (this.parent) {
  15306. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15307. invertParentWorldMatrix.invert();
  15308. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15309. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15310. }
  15311. else {
  15312. this.position.x = absolutePositionX;
  15313. this.position.y = absolutePositionY;
  15314. this.position.z = absolutePositionZ;
  15315. }
  15316. return this;
  15317. };
  15318. /**
  15319. * Sets the mesh position in its local space.
  15320. * Returns the AbstractMesh.
  15321. */
  15322. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15323. this.computeWorldMatrix();
  15324. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15325. return this;
  15326. };
  15327. /**
  15328. * Returns the mesh position in the local space from the current World matrix values.
  15329. * Returns a new Vector3.
  15330. */
  15331. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15332. this.computeWorldMatrix();
  15333. var invLocalWorldMatrix = this._localWorld.clone();
  15334. invLocalWorldMatrix.invert();
  15335. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15336. };
  15337. /**
  15338. * Translates the mesh along the passed Vector3 in its local space.
  15339. * Returns the AbstractMesh.
  15340. */
  15341. TransformNode.prototype.locallyTranslate = function (vector3) {
  15342. this.computeWorldMatrix(true);
  15343. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15344. return this;
  15345. };
  15346. /**
  15347. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  15348. * @param targetPoint the position (must be in same space as current mesh) to look at
  15349. * @param yawCor optional yaw (y-axis) correction in radians
  15350. * @param pitchCor optional pitch (x-axis) correction in radians
  15351. * @param rollCor optional roll (z-axis) correction in radians
  15352. * @param space the choosen space of the target
  15353. * @returns the TransformNode.
  15354. */
  15355. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  15356. if (yawCor === void 0) { yawCor = 0; }
  15357. if (pitchCor === void 0) { pitchCor = 0; }
  15358. if (rollCor === void 0) { rollCor = 0; }
  15359. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15360. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  15361. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  15362. targetPoint.subtractToRef(pos, dv);
  15363. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  15364. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  15365. var pitch = Math.atan2(dv.y, len);
  15366. if (this.rotationQuaternion) {
  15367. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  15368. }
  15369. else {
  15370. this.rotation.x = pitch + pitchCor;
  15371. this.rotation.y = yaw + yawCor;
  15372. this.rotation.z = rollCor;
  15373. }
  15374. return this;
  15375. };
  15376. /**
  15377. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  15378. * This Vector3 is expressed in the World space.
  15379. */
  15380. TransformNode.prototype.getDirection = function (localAxis) {
  15381. var result = BABYLON.Vector3.Zero();
  15382. this.getDirectionToRef(localAxis, result);
  15383. return result;
  15384. };
  15385. /**
  15386. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  15387. * localAxis is expressed in the mesh local space.
  15388. * result is computed in the Wordl space from the mesh World matrix.
  15389. * Returns the AbstractMesh.
  15390. */
  15391. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  15392. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15393. return this;
  15394. };
  15395. /**
  15396. * Sets a new pivot point to the current node
  15397. * @param point defines the new pivot point to use
  15398. * @param space defines if the point is in world or local space (local by default)
  15399. * @returns the current TransformNode
  15400. */
  15401. TransformNode.prototype.setPivotPoint = function (point, space) {
  15402. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15403. if (this.getScene().getRenderId() == 0) {
  15404. this.computeWorldMatrix(true);
  15405. }
  15406. var wm = this.getWorldMatrix();
  15407. if (space == BABYLON.Space.WORLD) {
  15408. var tmat = BABYLON.Tmp.Matrix[0];
  15409. wm.invertToRef(tmat);
  15410. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  15411. }
  15412. return this.setPivotMatrix(BABYLON.Matrix.Translation(point.x, point.y, point.z), true);
  15413. };
  15414. /**
  15415. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  15416. */
  15417. TransformNode.prototype.getPivotPoint = function () {
  15418. var point = BABYLON.Vector3.Zero();
  15419. this.getPivotPointToRef(point);
  15420. return point;
  15421. };
  15422. /**
  15423. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  15424. * Returns the AbstractMesh.
  15425. */
  15426. TransformNode.prototype.getPivotPointToRef = function (result) {
  15427. result.x = -this._pivotMatrix.m[12];
  15428. result.y = -this._pivotMatrix.m[13];
  15429. result.z = -this._pivotMatrix.m[14];
  15430. return this;
  15431. };
  15432. /**
  15433. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  15434. */
  15435. TransformNode.prototype.getAbsolutePivotPoint = function () {
  15436. var point = BABYLON.Vector3.Zero();
  15437. this.getAbsolutePivotPointToRef(point);
  15438. return point;
  15439. };
  15440. /**
  15441. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  15442. * Returns the AbstractMesh.
  15443. */
  15444. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  15445. result.x = this._pivotMatrix.m[12];
  15446. result.y = this._pivotMatrix.m[13];
  15447. result.z = this._pivotMatrix.m[14];
  15448. this.getPivotPointToRef(result);
  15449. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  15450. return this;
  15451. };
  15452. /**
  15453. * Defines the passed node as the parent of the current node.
  15454. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  15455. * Returns the TransformNode.
  15456. */
  15457. TransformNode.prototype.setParent = function (node) {
  15458. if (node === null) {
  15459. var rotation = BABYLON.Tmp.Quaternion[0];
  15460. var position = BABYLON.Tmp.Vector3[0];
  15461. var scale = BABYLON.Tmp.Vector3[1];
  15462. if (this.parent && this.parent.computeWorldMatrix) {
  15463. this.parent.computeWorldMatrix(true);
  15464. }
  15465. this.computeWorldMatrix(true);
  15466. this.getWorldMatrix().decompose(scale, rotation, position);
  15467. if (this.rotationQuaternion) {
  15468. this.rotationQuaternion.copyFrom(rotation);
  15469. }
  15470. else {
  15471. rotation.toEulerAnglesToRef(this.rotation);
  15472. }
  15473. this.scaling.x = scale.x;
  15474. this.scaling.y = scale.y;
  15475. this.scaling.z = scale.z;
  15476. this.position.x = position.x;
  15477. this.position.y = position.y;
  15478. this.position.z = position.z;
  15479. }
  15480. else {
  15481. var rotation = BABYLON.Tmp.Quaternion[0];
  15482. var position = BABYLON.Tmp.Vector3[0];
  15483. var scale = BABYLON.Tmp.Vector3[1];
  15484. var diffMatrix = BABYLON.Tmp.Matrix[0];
  15485. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  15486. this.computeWorldMatrix(true);
  15487. node.computeWorldMatrix(true);
  15488. node.getWorldMatrix().invertToRef(invParentMatrix);
  15489. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  15490. diffMatrix.decompose(scale, rotation, position);
  15491. if (this.rotationQuaternion) {
  15492. this.rotationQuaternion.copyFrom(rotation);
  15493. }
  15494. else {
  15495. rotation.toEulerAnglesToRef(this.rotation);
  15496. }
  15497. this.position.x = position.x;
  15498. this.position.y = position.y;
  15499. this.position.z = position.z;
  15500. this.scaling.x = scale.x;
  15501. this.scaling.y = scale.y;
  15502. this.scaling.z = scale.z;
  15503. }
  15504. this.parent = node;
  15505. return this;
  15506. };
  15507. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  15508. get: function () {
  15509. return this._nonUniformScaling;
  15510. },
  15511. enumerable: true,
  15512. configurable: true
  15513. });
  15514. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  15515. if (this._nonUniformScaling === value) {
  15516. return false;
  15517. }
  15518. this._nonUniformScaling = true;
  15519. return true;
  15520. };
  15521. /**
  15522. * Attach the current TransformNode to another TransformNode associated with a bone
  15523. * @param bone Bone affecting the TransformNode
  15524. * @param affectedTransformNode TransformNode associated with the bone
  15525. */
  15526. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  15527. this._transformToBoneReferal = affectedTransformNode;
  15528. this.parent = bone;
  15529. if (bone.getWorldMatrix().determinant() < 0) {
  15530. this.scalingDeterminant *= -1;
  15531. }
  15532. return this;
  15533. };
  15534. TransformNode.prototype.detachFromBone = function () {
  15535. if (!this.parent) {
  15536. return this;
  15537. }
  15538. if (this.parent.getWorldMatrix().determinant() < 0) {
  15539. this.scalingDeterminant *= -1;
  15540. }
  15541. this._transformToBoneReferal = null;
  15542. this.parent = null;
  15543. return this;
  15544. };
  15545. /**
  15546. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  15547. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15548. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15549. * The passed axis is also normalized.
  15550. * Returns the AbstractMesh.
  15551. */
  15552. TransformNode.prototype.rotate = function (axis, amount, space) {
  15553. axis.normalize();
  15554. if (!this.rotationQuaternion) {
  15555. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15556. this.rotation = BABYLON.Vector3.Zero();
  15557. }
  15558. var rotationQuaternion;
  15559. if (!space || space === BABYLON.Space.LOCAL) {
  15560. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15561. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  15562. }
  15563. else {
  15564. if (this.parent) {
  15565. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15566. invertParentWorldMatrix.invert();
  15567. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  15568. }
  15569. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15570. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15571. }
  15572. return this;
  15573. };
  15574. /**
  15575. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  15576. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15577. * The passed axis is also normalized.
  15578. * Returns the AbstractMesh.
  15579. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  15580. */
  15581. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  15582. axis.normalize();
  15583. if (!this.rotationQuaternion) {
  15584. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15585. this.rotation.copyFromFloats(0, 0, 0);
  15586. }
  15587. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  15588. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  15589. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  15590. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  15591. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  15592. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  15593. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  15594. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  15595. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15596. return this;
  15597. };
  15598. /**
  15599. * Translates the mesh along the axis vector for the passed distance in the given space.
  15600. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15601. * Returns the AbstractMesh.
  15602. */
  15603. TransformNode.prototype.translate = function (axis, distance, space) {
  15604. var displacementVector = axis.scale(distance);
  15605. if (!space || space === BABYLON.Space.LOCAL) {
  15606. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  15607. this.setPositionWithLocalVector(tempV3);
  15608. }
  15609. else {
  15610. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15611. }
  15612. return this;
  15613. };
  15614. /**
  15615. * Adds a rotation step to the mesh current rotation.
  15616. * x, y, z are Euler angles expressed in radians.
  15617. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15618. * This means this rotation is made in the mesh local space only.
  15619. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15620. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15621. * ```javascript
  15622. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15623. * ```
  15624. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15625. * 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.
  15626. * Returns the AbstractMesh.
  15627. */
  15628. TransformNode.prototype.addRotation = function (x, y, z) {
  15629. var rotationQuaternion;
  15630. if (this.rotationQuaternion) {
  15631. rotationQuaternion = this.rotationQuaternion;
  15632. }
  15633. else {
  15634. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15635. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15636. }
  15637. var accumulation = BABYLON.Tmp.Quaternion[0];
  15638. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15639. rotationQuaternion.multiplyInPlace(accumulation);
  15640. if (!this.rotationQuaternion) {
  15641. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15642. }
  15643. return this;
  15644. };
  15645. /**
  15646. * Computes the mesh World matrix and returns it.
  15647. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15648. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15649. * If the parameter `force`is set to `true`, the actual computation is done.
  15650. * Returns the mesh World Matrix.
  15651. */
  15652. TransformNode.prototype.computeWorldMatrix = function (force) {
  15653. if (this._isWorldMatrixFrozen) {
  15654. return this._worldMatrix;
  15655. }
  15656. if (!force && this.isSynchronized(true)) {
  15657. return this._worldMatrix;
  15658. }
  15659. this._cache.position.copyFrom(this.position);
  15660. this._cache.scaling.copyFrom(this.scaling);
  15661. this._cache.pivotMatrixUpdated = false;
  15662. this._cache.billboardMode = this.billboardMode;
  15663. this._currentRenderId = this.getScene().getRenderId();
  15664. this._isDirty = false;
  15665. // Scaling
  15666. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15667. // Rotation
  15668. //rotate, if quaternion is set and rotation was used
  15669. if (this.rotationQuaternion) {
  15670. var len = this.rotation.length();
  15671. if (len) {
  15672. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15673. this.rotation.copyFromFloats(0, 0, 0);
  15674. }
  15675. }
  15676. if (this.rotationQuaternion) {
  15677. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15678. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15679. }
  15680. else {
  15681. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15682. this._cache.rotation.copyFrom(this.rotation);
  15683. }
  15684. // Translation
  15685. var camera = this.getScene().activeCamera;
  15686. if (this.infiniteDistance && !this.parent && camera) {
  15687. var cameraWorldMatrix = camera.getWorldMatrix();
  15688. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15689. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15690. }
  15691. else {
  15692. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15693. }
  15694. // Composing transformations
  15695. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15696. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15697. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15698. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15699. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15700. // Need to decompose each rotation here
  15701. var currentPosition = BABYLON.Tmp.Vector3[3];
  15702. if (this.parent && this.parent.getWorldMatrix) {
  15703. if (this._transformToBoneReferal) {
  15704. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15705. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15706. }
  15707. else {
  15708. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15709. }
  15710. }
  15711. else {
  15712. currentPosition.copyFrom(this.position);
  15713. }
  15714. currentPosition.subtractInPlace(camera.globalPosition);
  15715. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15716. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15717. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15718. }
  15719. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15720. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15721. }
  15722. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15723. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15724. }
  15725. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15726. }
  15727. else {
  15728. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15729. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15730. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15731. }
  15732. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15733. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15734. }
  15735. // Local world
  15736. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15737. // Parent
  15738. if (this.parent && this.parent.getWorldMatrix) {
  15739. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15740. if (this._transformToBoneReferal) {
  15741. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15742. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15743. }
  15744. else {
  15745. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15746. }
  15747. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15748. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15749. this._worldMatrix.copyFrom(this._localWorld);
  15750. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15751. }
  15752. else {
  15753. if (this._transformToBoneReferal) {
  15754. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15755. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15756. }
  15757. else {
  15758. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15759. }
  15760. }
  15761. this._markSyncedWithParent();
  15762. }
  15763. else {
  15764. this._worldMatrix.copyFrom(this._localWorld);
  15765. }
  15766. // Post multiply inverse of pivotMatrix
  15767. if (this._postMultiplyPivotMatrix) {
  15768. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15769. }
  15770. // Normal matrix
  15771. if (this.scaling.isNonUniform) {
  15772. this._updateNonUniformScalingState(true);
  15773. }
  15774. else if (this.parent && this.parent._nonUniformScaling) {
  15775. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15776. }
  15777. else {
  15778. this._updateNonUniformScalingState(false);
  15779. }
  15780. this._afterComputeWorldMatrix();
  15781. // Absolute position
  15782. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15783. // Callbacks
  15784. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15785. if (!this._poseMatrix) {
  15786. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15787. }
  15788. // Cache the determinant
  15789. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15790. return this._worldMatrix;
  15791. };
  15792. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15793. };
  15794. /**
  15795. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15796. * @param func: callback function to add
  15797. *
  15798. * Returns the TransformNode.
  15799. */
  15800. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15801. this.onAfterWorldMatrixUpdateObservable.add(func);
  15802. return this;
  15803. };
  15804. /**
  15805. * Removes a registered callback function.
  15806. * Returns the TransformNode.
  15807. */
  15808. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15809. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15810. return this;
  15811. };
  15812. /**
  15813. * Clone the current transform node
  15814. * Returns the new transform node
  15815. * @param name Name of the new clone
  15816. * @param newParent New parent for the clone
  15817. * @param doNotCloneChildren Do not clone children hierarchy
  15818. */
  15819. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15820. var _this = this;
  15821. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15822. result.name = name;
  15823. result.id = name;
  15824. if (newParent) {
  15825. result.parent = newParent;
  15826. }
  15827. if (!doNotCloneChildren) {
  15828. // Children
  15829. var directDescendants = this.getDescendants(true);
  15830. for (var index = 0; index < directDescendants.length; index++) {
  15831. var child = directDescendants[index];
  15832. if (child.clone) {
  15833. child.clone(name + "." + child.name, result);
  15834. }
  15835. }
  15836. }
  15837. return result;
  15838. };
  15839. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15840. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15841. serializationObject.type = this.getClassName();
  15842. // Parent
  15843. if (this.parent) {
  15844. serializationObject.parentId = this.parent.id;
  15845. }
  15846. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15847. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15848. }
  15849. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15850. serializationObject.isEnabled = this.isEnabled();
  15851. // Parent
  15852. if (this.parent) {
  15853. serializationObject.parentId = this.parent.id;
  15854. }
  15855. return serializationObject;
  15856. };
  15857. // Statics
  15858. /**
  15859. * Returns a new TransformNode object parsed from the source provided.
  15860. * The parameter `parsedMesh` is the source.
  15861. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15862. */
  15863. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15864. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15865. if (BABYLON.Tags) {
  15866. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15867. }
  15868. if (parsedTransformNode.localMatrix) {
  15869. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15870. }
  15871. else if (parsedTransformNode.pivotMatrix) {
  15872. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15873. }
  15874. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15875. // Parent
  15876. if (parsedTransformNode.parentId) {
  15877. transformNode._waitingParentId = parsedTransformNode.parentId;
  15878. }
  15879. return transformNode;
  15880. };
  15881. /**
  15882. * Disposes the TransformNode.
  15883. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15884. * Returns nothing.
  15885. */
  15886. TransformNode.prototype.dispose = function (doNotRecurse) {
  15887. // Animations
  15888. this.getScene().stopAnimation(this);
  15889. // Remove from scene
  15890. this.getScene().removeTransformNode(this);
  15891. if (!doNotRecurse) {
  15892. // Children
  15893. var objects = this.getDescendants(true);
  15894. for (var index = 0; index < objects.length; index++) {
  15895. objects[index].dispose();
  15896. }
  15897. }
  15898. else {
  15899. var childMeshes = this.getChildMeshes(true);
  15900. for (index = 0; index < childMeshes.length; index++) {
  15901. var child = childMeshes[index];
  15902. child.parent = null;
  15903. child.computeWorldMatrix(true);
  15904. }
  15905. }
  15906. this.onAfterWorldMatrixUpdateObservable.clear();
  15907. _super.prototype.dispose.call(this);
  15908. };
  15909. // Statics
  15910. TransformNode.BILLBOARDMODE_NONE = 0;
  15911. TransformNode.BILLBOARDMODE_X = 1;
  15912. TransformNode.BILLBOARDMODE_Y = 2;
  15913. TransformNode.BILLBOARDMODE_Z = 4;
  15914. TransformNode.BILLBOARDMODE_ALL = 7;
  15915. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15916. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15917. __decorate([
  15918. BABYLON.serializeAsVector3()
  15919. ], TransformNode.prototype, "_rotation", void 0);
  15920. __decorate([
  15921. BABYLON.serializeAsQuaternion()
  15922. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15923. __decorate([
  15924. BABYLON.serializeAsVector3()
  15925. ], TransformNode.prototype, "_scaling", void 0);
  15926. __decorate([
  15927. BABYLON.serialize()
  15928. ], TransformNode.prototype, "billboardMode", void 0);
  15929. __decorate([
  15930. BABYLON.serialize()
  15931. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15932. __decorate([
  15933. BABYLON.serialize()
  15934. ], TransformNode.prototype, "infiniteDistance", void 0);
  15935. __decorate([
  15936. BABYLON.serializeAsVector3()
  15937. ], TransformNode.prototype, "position", void 0);
  15938. return TransformNode;
  15939. }(BABYLON.Node));
  15940. BABYLON.TransformNode = TransformNode;
  15941. })(BABYLON || (BABYLON = {}));
  15942. //# sourceMappingURL=babylon.transformNode.js.map
  15943. var BABYLON;
  15944. (function (BABYLON) {
  15945. var AbstractMesh = /** @class */ (function (_super) {
  15946. __extends(AbstractMesh, _super);
  15947. // Constructor
  15948. function AbstractMesh(name, scene) {
  15949. if (scene === void 0) { scene = null; }
  15950. var _this = _super.call(this, name, scene, false) || this;
  15951. _this._facetNb = 0; // facet number
  15952. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15953. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15954. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15955. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15956. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15957. _this._subDiv = {
  15958. max: 1,
  15959. X: 1,
  15960. Y: 1,
  15961. Z: 1
  15962. };
  15963. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15964. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15965. // Events
  15966. /**
  15967. * An event triggered when this mesh collides with another one
  15968. * @type {BABYLON.Observable}
  15969. */
  15970. _this.onCollideObservable = new BABYLON.Observable();
  15971. /**
  15972. * An event triggered when the collision's position changes
  15973. * @type {BABYLON.Observable}
  15974. */
  15975. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15976. /**
  15977. * An event triggered when material is changed
  15978. * @type {BABYLON.Observable}
  15979. */
  15980. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15981. // Properties
  15982. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15983. /**
  15984. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15985. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15986. * or
  15987. * 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.
  15988. * for more info check WebGl documentations
  15989. */
  15990. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15991. /**
  15992. * 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:
  15993. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15994. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15995. * 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.
  15996. */
  15997. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15998. /**
  15999. * 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.
  16000. * The default value is -1 which means don't break the query and wait till the result.
  16001. */
  16002. _this.occlusionRetryCount = -1;
  16003. _this._occlusionInternalRetryCounter = 0;
  16004. _this._isOccluded = false;
  16005. _this._isOcclusionQueryInProgress = false;
  16006. _this._visibility = 1.0;
  16007. _this.alphaIndex = Number.MAX_VALUE;
  16008. _this.isVisible = true;
  16009. _this.isPickable = true;
  16010. _this.showBoundingBox = false;
  16011. _this.showSubMeshesBoundingBox = false;
  16012. _this.isBlocker = false;
  16013. _this.enablePointerMoveEvents = false;
  16014. _this.renderingGroupId = 0;
  16015. _this._receiveShadows = false;
  16016. _this.renderOutline = false;
  16017. _this.outlineColor = BABYLON.Color3.Red();
  16018. _this.outlineWidth = 0.02;
  16019. _this.renderOverlay = false;
  16020. _this.overlayColor = BABYLON.Color3.Red();
  16021. _this.overlayAlpha = 0.5;
  16022. _this._hasVertexAlpha = false;
  16023. _this._useVertexColors = true;
  16024. _this._computeBonesUsingShaders = true;
  16025. _this._numBoneInfluencers = 4;
  16026. _this._applyFog = true;
  16027. _this.useOctreeForRenderingSelection = true;
  16028. _this.useOctreeForPicking = true;
  16029. _this.useOctreeForCollisions = true;
  16030. _this._layerMask = 0x0FFFFFFF;
  16031. /**
  16032. * True if the mesh must be rendered in any case.
  16033. */
  16034. _this.alwaysSelectAsActiveMesh = false;
  16035. /**
  16036. * This scene's action manager
  16037. * @type {BABYLON.ActionManager}
  16038. */
  16039. _this.actionManager = null;
  16040. // Physics
  16041. _this.physicsImpostor = null;
  16042. // Collisions
  16043. _this._checkCollisions = false;
  16044. _this._collisionMask = -1;
  16045. _this._collisionGroup = -1;
  16046. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16047. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16048. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16049. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16050. // Edges
  16051. _this.edgesWidth = 1;
  16052. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16053. // Cache
  16054. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16055. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16056. _this._isDisposed = false;
  16057. _this._renderId = 0;
  16058. _this._intersectionsInProgress = new Array();
  16059. _this._unIndexed = false;
  16060. _this._lightSources = new Array();
  16061. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16062. if (collidedMesh === void 0) { collidedMesh = null; }
  16063. //TODO move this to the collision coordinator!
  16064. if (_this.getScene().workerCollisions)
  16065. newPosition.multiplyInPlace(_this._collider._radius);
  16066. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16067. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16068. _this.position.addInPlace(_this._diffPositionForCollisions);
  16069. }
  16070. if (collidedMesh) {
  16071. _this.onCollideObservable.notifyObservers(collidedMesh);
  16072. }
  16073. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16074. };
  16075. _this.getScene().addMesh(_this);
  16076. _this._resyncLightSources();
  16077. return _this;
  16078. }
  16079. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16080. get: function () {
  16081. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16082. },
  16083. enumerable: true,
  16084. configurable: true
  16085. });
  16086. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16087. get: function () {
  16088. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16089. },
  16090. enumerable: true,
  16091. configurable: true
  16092. });
  16093. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16094. get: function () {
  16095. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16096. },
  16097. enumerable: true,
  16098. configurable: true
  16099. });
  16100. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16101. get: function () {
  16102. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16103. },
  16104. enumerable: true,
  16105. configurable: true
  16106. });
  16107. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16108. get: function () {
  16109. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16110. },
  16111. enumerable: true,
  16112. configurable: true
  16113. });
  16114. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16115. /**
  16116. * Read-only : the number of facets in the mesh
  16117. */
  16118. get: function () {
  16119. return this._facetNb;
  16120. },
  16121. enumerable: true,
  16122. configurable: true
  16123. });
  16124. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16125. /**
  16126. * The number (integer) of subdivisions per axis in the partioning space
  16127. */
  16128. get: function () {
  16129. return this._partitioningSubdivisions;
  16130. },
  16131. set: function (nb) {
  16132. this._partitioningSubdivisions = nb;
  16133. },
  16134. enumerable: true,
  16135. configurable: true
  16136. });
  16137. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16138. /**
  16139. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16140. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16141. */
  16142. get: function () {
  16143. return this._partitioningBBoxRatio;
  16144. },
  16145. set: function (ratio) {
  16146. this._partitioningBBoxRatio = ratio;
  16147. },
  16148. enumerable: true,
  16149. configurable: true
  16150. });
  16151. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16152. /**
  16153. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16154. * Works only for updatable meshes.
  16155. * Doesn't work with multi-materials.
  16156. */
  16157. get: function () {
  16158. return this._facetDepthSort;
  16159. },
  16160. set: function (sort) {
  16161. this._facetDepthSort = sort;
  16162. },
  16163. enumerable: true,
  16164. configurable: true
  16165. });
  16166. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16167. /**
  16168. * The location (Vector3) where the facet depth sort must be computed from.
  16169. * By default, the active camera position.
  16170. * Used only when facet depth sort is enabled.
  16171. */
  16172. get: function () {
  16173. return this._facetDepthSortFrom;
  16174. },
  16175. set: function (location) {
  16176. this._facetDepthSortFrom = location;
  16177. },
  16178. enumerable: true,
  16179. configurable: true
  16180. });
  16181. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16182. /**
  16183. * Read-only boolean : is the feature facetData enabled ?
  16184. */
  16185. get: function () {
  16186. return this._facetDataEnabled;
  16187. },
  16188. enumerable: true,
  16189. configurable: true
  16190. });
  16191. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16192. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16193. return false;
  16194. }
  16195. this._markSubMeshesAsMiscDirty();
  16196. return true;
  16197. };
  16198. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16199. set: function (callback) {
  16200. if (this._onCollideObserver) {
  16201. this.onCollideObservable.remove(this._onCollideObserver);
  16202. }
  16203. this._onCollideObserver = this.onCollideObservable.add(callback);
  16204. },
  16205. enumerable: true,
  16206. configurable: true
  16207. });
  16208. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16209. set: function (callback) {
  16210. if (this._onCollisionPositionChangeObserver) {
  16211. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16212. }
  16213. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16214. },
  16215. enumerable: true,
  16216. configurable: true
  16217. });
  16218. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16219. /**
  16220. * 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.
  16221. */
  16222. get: function () {
  16223. return this._isOccluded;
  16224. },
  16225. set: function (value) {
  16226. this._isOccluded = value;
  16227. },
  16228. enumerable: true,
  16229. configurable: true
  16230. });
  16231. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16232. /**
  16233. * Flag to check the progress status of the query
  16234. */
  16235. get: function () {
  16236. return this._isOcclusionQueryInProgress;
  16237. },
  16238. enumerable: true,
  16239. configurable: true
  16240. });
  16241. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16242. /**
  16243. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16244. */
  16245. get: function () {
  16246. return this._visibility;
  16247. },
  16248. /**
  16249. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16250. */
  16251. set: function (value) {
  16252. if (this._visibility === value) {
  16253. return;
  16254. }
  16255. this._visibility = value;
  16256. this._markSubMeshesAsMiscDirty();
  16257. },
  16258. enumerable: true,
  16259. configurable: true
  16260. });
  16261. Object.defineProperty(AbstractMesh.prototype, "material", {
  16262. get: function () {
  16263. return this._material;
  16264. },
  16265. set: function (value) {
  16266. if (this._material === value) {
  16267. return;
  16268. }
  16269. this._material = value;
  16270. if (this.onMaterialChangedObservable.hasObservers) {
  16271. this.onMaterialChangedObservable.notifyObservers(this);
  16272. }
  16273. if (!this.subMeshes) {
  16274. return;
  16275. }
  16276. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16277. var subMesh = _a[_i];
  16278. subMesh.setEffect(null);
  16279. }
  16280. },
  16281. enumerable: true,
  16282. configurable: true
  16283. });
  16284. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16285. get: function () {
  16286. return this._receiveShadows;
  16287. },
  16288. set: function (value) {
  16289. if (this._receiveShadows === value) {
  16290. return;
  16291. }
  16292. this._receiveShadows = value;
  16293. this._markSubMeshesAsLightDirty();
  16294. },
  16295. enumerable: true,
  16296. configurable: true
  16297. });
  16298. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16299. get: function () {
  16300. return this._hasVertexAlpha;
  16301. },
  16302. set: function (value) {
  16303. if (this._hasVertexAlpha === value) {
  16304. return;
  16305. }
  16306. this._hasVertexAlpha = value;
  16307. this._markSubMeshesAsAttributesDirty();
  16308. this._markSubMeshesAsMiscDirty();
  16309. },
  16310. enumerable: true,
  16311. configurable: true
  16312. });
  16313. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16314. get: function () {
  16315. return this._useVertexColors;
  16316. },
  16317. set: function (value) {
  16318. if (this._useVertexColors === value) {
  16319. return;
  16320. }
  16321. this._useVertexColors = value;
  16322. this._markSubMeshesAsAttributesDirty();
  16323. },
  16324. enumerable: true,
  16325. configurable: true
  16326. });
  16327. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16328. get: function () {
  16329. return this._computeBonesUsingShaders;
  16330. },
  16331. set: function (value) {
  16332. if (this._computeBonesUsingShaders === value) {
  16333. return;
  16334. }
  16335. this._computeBonesUsingShaders = value;
  16336. this._markSubMeshesAsAttributesDirty();
  16337. },
  16338. enumerable: true,
  16339. configurable: true
  16340. });
  16341. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16342. get: function () {
  16343. return this._numBoneInfluencers;
  16344. },
  16345. set: function (value) {
  16346. if (this._numBoneInfluencers === value) {
  16347. return;
  16348. }
  16349. this._numBoneInfluencers = value;
  16350. this._markSubMeshesAsAttributesDirty();
  16351. },
  16352. enumerable: true,
  16353. configurable: true
  16354. });
  16355. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  16356. get: function () {
  16357. return this._applyFog;
  16358. },
  16359. set: function (value) {
  16360. if (this._applyFog === value) {
  16361. return;
  16362. }
  16363. this._applyFog = value;
  16364. this._markSubMeshesAsMiscDirty();
  16365. },
  16366. enumerable: true,
  16367. configurable: true
  16368. });
  16369. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  16370. get: function () {
  16371. return this._layerMask;
  16372. },
  16373. set: function (value) {
  16374. if (value === this._layerMask) {
  16375. return;
  16376. }
  16377. this._layerMask = value;
  16378. this._resyncLightSources();
  16379. },
  16380. enumerable: true,
  16381. configurable: true
  16382. });
  16383. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  16384. get: function () {
  16385. return this._collisionMask;
  16386. },
  16387. set: function (mask) {
  16388. this._collisionMask = !isNaN(mask) ? mask : -1;
  16389. },
  16390. enumerable: true,
  16391. configurable: true
  16392. });
  16393. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  16394. get: function () {
  16395. return this._collisionGroup;
  16396. },
  16397. set: function (mask) {
  16398. this._collisionGroup = !isNaN(mask) ? mask : -1;
  16399. },
  16400. enumerable: true,
  16401. configurable: true
  16402. });
  16403. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  16404. get: function () {
  16405. return null;
  16406. },
  16407. enumerable: true,
  16408. configurable: true
  16409. });
  16410. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  16411. get: function () {
  16412. return this._skeleton;
  16413. },
  16414. set: function (value) {
  16415. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  16416. this._skeleton._unregisterMeshWithPoseMatrix(this);
  16417. }
  16418. if (value && value.needInitialSkinMatrix) {
  16419. value._registerMeshWithPoseMatrix(this);
  16420. }
  16421. this._skeleton = value;
  16422. if (!this._skeleton) {
  16423. this._bonesTransformMatrices = null;
  16424. }
  16425. this._markSubMeshesAsAttributesDirty();
  16426. },
  16427. enumerable: true,
  16428. configurable: true
  16429. });
  16430. /**
  16431. * Boolean : true if the mesh has been disposed.
  16432. */
  16433. AbstractMesh.prototype.isDisposed = function () {
  16434. return this._isDisposed;
  16435. };
  16436. /**
  16437. * Returns the string "AbstractMesh"
  16438. */
  16439. AbstractMesh.prototype.getClassName = function () {
  16440. return "AbstractMesh";
  16441. };
  16442. /**
  16443. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16444. */
  16445. AbstractMesh.prototype.toString = function (fullDetails) {
  16446. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  16447. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  16448. if (this._skeleton) {
  16449. ret += ", skeleton: " + this._skeleton.name;
  16450. }
  16451. if (fullDetails) {
  16452. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  16453. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  16454. }
  16455. return ret;
  16456. };
  16457. AbstractMesh.prototype._rebuild = function () {
  16458. if (this._occlusionQuery) {
  16459. this._occlusionQuery = null;
  16460. }
  16461. if (this._edgesRenderer) {
  16462. this._edgesRenderer._rebuild();
  16463. }
  16464. if (!this.subMeshes) {
  16465. return;
  16466. }
  16467. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16468. var subMesh = _a[_i];
  16469. subMesh._rebuild();
  16470. }
  16471. };
  16472. AbstractMesh.prototype._resyncLightSources = function () {
  16473. this._lightSources.length = 0;
  16474. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  16475. var light = _a[_i];
  16476. if (!light.isEnabled()) {
  16477. continue;
  16478. }
  16479. if (light.canAffectMesh(this)) {
  16480. this._lightSources.push(light);
  16481. }
  16482. }
  16483. this._markSubMeshesAsLightDirty();
  16484. };
  16485. AbstractMesh.prototype._resyncLighSource = function (light) {
  16486. var isIn = light.isEnabled() && light.canAffectMesh(this);
  16487. var index = this._lightSources.indexOf(light);
  16488. if (index === -1) {
  16489. if (!isIn) {
  16490. return;
  16491. }
  16492. this._lightSources.push(light);
  16493. }
  16494. else {
  16495. if (isIn) {
  16496. return;
  16497. }
  16498. this._lightSources.splice(index, 1);
  16499. }
  16500. this._markSubMeshesAsLightDirty();
  16501. };
  16502. AbstractMesh.prototype._removeLightSource = function (light) {
  16503. var index = this._lightSources.indexOf(light);
  16504. if (index === -1) {
  16505. return;
  16506. }
  16507. this._lightSources.splice(index, 1);
  16508. this._markSubMeshesAsLightDirty();
  16509. };
  16510. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  16511. if (!this.subMeshes) {
  16512. return;
  16513. }
  16514. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16515. var subMesh = _a[_i];
  16516. if (subMesh._materialDefines) {
  16517. func(subMesh._materialDefines);
  16518. }
  16519. }
  16520. };
  16521. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  16522. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  16523. };
  16524. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  16525. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  16526. };
  16527. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  16528. if (!this.subMeshes) {
  16529. return;
  16530. }
  16531. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16532. var subMesh = _a[_i];
  16533. var material = subMesh.getMaterial();
  16534. if (material) {
  16535. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  16536. }
  16537. }
  16538. };
  16539. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  16540. /**
  16541. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16542. * Default : (1.0, 1.0, 1.0)
  16543. */
  16544. get: function () {
  16545. return this._scaling;
  16546. },
  16547. /**
  16548. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16549. * Default : (1.0, 1.0, 1.0)
  16550. */
  16551. set: function (newScaling) {
  16552. this._scaling = newScaling;
  16553. if (this.physicsImpostor) {
  16554. this.physicsImpostor.forceUpdate();
  16555. }
  16556. },
  16557. enumerable: true,
  16558. configurable: true
  16559. });
  16560. // Methods
  16561. /**
  16562. * Disables the mesh edger rendering mode.
  16563. * Returns the AbstractMesh.
  16564. */
  16565. AbstractMesh.prototype.disableEdgesRendering = function () {
  16566. if (this._edgesRenderer) {
  16567. this._edgesRenderer.dispose();
  16568. this._edgesRenderer = null;
  16569. }
  16570. return this;
  16571. };
  16572. /**
  16573. * Enables the edge rendering mode on the mesh.
  16574. * This mode makes the mesh edges visible.
  16575. * Returns the AbstractMesh.
  16576. */
  16577. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  16578. if (epsilon === void 0) { epsilon = 0.95; }
  16579. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  16580. this.disableEdgesRendering();
  16581. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  16582. return this;
  16583. };
  16584. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  16585. /**
  16586. * Returns true if the mesh is blocked. Used by the class Mesh.
  16587. * Returns the boolean `false` by default.
  16588. */
  16589. get: function () {
  16590. return false;
  16591. },
  16592. enumerable: true,
  16593. configurable: true
  16594. });
  16595. /**
  16596. * Returns the mesh itself by default, used by the class Mesh.
  16597. * Returned type : AbstractMesh
  16598. */
  16599. AbstractMesh.prototype.getLOD = function (camera) {
  16600. return this;
  16601. };
  16602. /**
  16603. * Returns 0 by default, used by the class Mesh.
  16604. * Returns an integer.
  16605. */
  16606. AbstractMesh.prototype.getTotalVertices = function () {
  16607. return 0;
  16608. };
  16609. /**
  16610. * Returns null by default, used by the class Mesh.
  16611. * Returned type : integer array
  16612. */
  16613. AbstractMesh.prototype.getIndices = function () {
  16614. return null;
  16615. };
  16616. /**
  16617. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  16618. * Returned type : float array or Float32Array
  16619. */
  16620. AbstractMesh.prototype.getVerticesData = function (kind) {
  16621. return null;
  16622. };
  16623. /**
  16624. * Sets the vertex data of the mesh geometry for the requested `kind`.
  16625. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  16626. * The `data` are either a numeric array either a Float32Array.
  16627. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  16628. * 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).
  16629. * Note that a new underlying VertexBuffer object is created each call.
  16630. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16631. *
  16632. * Possible `kind` values :
  16633. * - BABYLON.VertexBuffer.PositionKind
  16634. * - BABYLON.VertexBuffer.UVKind
  16635. * - BABYLON.VertexBuffer.UV2Kind
  16636. * - BABYLON.VertexBuffer.UV3Kind
  16637. * - BABYLON.VertexBuffer.UV4Kind
  16638. * - BABYLON.VertexBuffer.UV5Kind
  16639. * - BABYLON.VertexBuffer.UV6Kind
  16640. * - BABYLON.VertexBuffer.ColorKind
  16641. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16642. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16643. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16644. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16645. *
  16646. * Returns the Mesh.
  16647. */
  16648. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16649. return this;
  16650. };
  16651. /**
  16652. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16653. * If the mesh has no geometry, it is simply returned as it is.
  16654. * The `data` are either a numeric array either a Float32Array.
  16655. * No new underlying VertexBuffer object is created.
  16656. * 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.
  16657. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16658. *
  16659. * Possible `kind` values :
  16660. * - BABYLON.VertexBuffer.PositionKind
  16661. * - BABYLON.VertexBuffer.UVKind
  16662. * - BABYLON.VertexBuffer.UV2Kind
  16663. * - BABYLON.VertexBuffer.UV3Kind
  16664. * - BABYLON.VertexBuffer.UV4Kind
  16665. * - BABYLON.VertexBuffer.UV5Kind
  16666. * - BABYLON.VertexBuffer.UV6Kind
  16667. * - BABYLON.VertexBuffer.ColorKind
  16668. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16669. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16670. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16671. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16672. *
  16673. * Returns the Mesh.
  16674. */
  16675. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16676. return this;
  16677. };
  16678. /**
  16679. * Sets the mesh indices.
  16680. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16681. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16682. * This method creates a new index buffer each call.
  16683. * Returns the Mesh.
  16684. */
  16685. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16686. return this;
  16687. };
  16688. /** Returns false by default, used by the class Mesh.
  16689. * Returns a boolean
  16690. */
  16691. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16692. return false;
  16693. };
  16694. /**
  16695. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16696. * Returns a BoundingInfo
  16697. */
  16698. AbstractMesh.prototype.getBoundingInfo = function () {
  16699. if (this._masterMesh) {
  16700. return this._masterMesh.getBoundingInfo();
  16701. }
  16702. if (!this._boundingInfo) {
  16703. // this._boundingInfo is being created here
  16704. this._updateBoundingInfo();
  16705. }
  16706. // cannot be null.
  16707. return this._boundingInfo;
  16708. };
  16709. /**
  16710. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16711. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16712. */
  16713. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16714. if (includeDescendants === void 0) { includeDescendants = true; }
  16715. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16716. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16717. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16718. if (maxDimension === 0) {
  16719. return this;
  16720. }
  16721. var scale = 1 / maxDimension;
  16722. this.scaling.scaleInPlace(scale);
  16723. return this;
  16724. };
  16725. /**
  16726. * Sets a mesh new object BoundingInfo.
  16727. * Returns the AbstractMesh.
  16728. */
  16729. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16730. this._boundingInfo = boundingInfo;
  16731. return this;
  16732. };
  16733. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16734. get: function () {
  16735. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16736. },
  16737. enumerable: true,
  16738. configurable: true
  16739. });
  16740. AbstractMesh.prototype._preActivate = function () {
  16741. };
  16742. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16743. };
  16744. AbstractMesh.prototype._activate = function (renderId) {
  16745. this._renderId = renderId;
  16746. };
  16747. /**
  16748. * Returns the latest update of the World matrix
  16749. * Returns a Matrix.
  16750. */
  16751. AbstractMesh.prototype.getWorldMatrix = function () {
  16752. if (this._masterMesh) {
  16753. return this._masterMesh.getWorldMatrix();
  16754. }
  16755. return _super.prototype.getWorldMatrix.call(this);
  16756. };
  16757. /**
  16758. * Returns the latest update of the World matrix determinant.
  16759. */
  16760. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16761. if (this._masterMesh) {
  16762. return this._masterMesh._getWorldMatrixDeterminant();
  16763. }
  16764. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16765. };
  16766. // ================================== Point of View Movement =================================
  16767. /**
  16768. * Perform relative position change from the point of view of behind the front of the mesh.
  16769. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16770. * Supports definition of mesh facing forward or backward.
  16771. * @param {number} amountRight
  16772. * @param {number} amountUp
  16773. * @param {number} amountForward
  16774. *
  16775. * Returns the AbstractMesh.
  16776. */
  16777. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16778. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16779. return this;
  16780. };
  16781. /**
  16782. * Calculate relative position change from the point of view of behind the front of the mesh.
  16783. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16784. * Supports definition of mesh facing forward or backward.
  16785. * @param {number} amountRight
  16786. * @param {number} amountUp
  16787. * @param {number} amountForward
  16788. *
  16789. * Returns a new Vector3.
  16790. */
  16791. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16792. var rotMatrix = new BABYLON.Matrix();
  16793. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16794. rotQuaternion.toRotationMatrix(rotMatrix);
  16795. var translationDelta = BABYLON.Vector3.Zero();
  16796. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16797. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16798. return translationDelta;
  16799. };
  16800. // ================================== Point of View Rotation =================================
  16801. /**
  16802. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16803. * Supports definition of mesh facing forward or backward.
  16804. * @param {number} flipBack
  16805. * @param {number} twirlClockwise
  16806. * @param {number} tiltRight
  16807. *
  16808. * Returns the AbstractMesh.
  16809. */
  16810. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16811. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16812. return this;
  16813. };
  16814. /**
  16815. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16816. * Supports definition of mesh facing forward or backward.
  16817. * @param {number} flipBack
  16818. * @param {number} twirlClockwise
  16819. * @param {number} tiltRight
  16820. *
  16821. * Returns a new Vector3.
  16822. */
  16823. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16824. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16825. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16826. };
  16827. /**
  16828. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16829. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16830. */
  16831. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16832. if (includeDescendants === void 0) { includeDescendants = true; }
  16833. this.computeWorldMatrix(true);
  16834. var min;
  16835. var max;
  16836. var boundingInfo = this.getBoundingInfo();
  16837. if (!this.subMeshes) {
  16838. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16839. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16840. }
  16841. else {
  16842. min = boundingInfo.boundingBox.minimumWorld;
  16843. max = boundingInfo.boundingBox.maximumWorld;
  16844. }
  16845. if (includeDescendants) {
  16846. var descendants = this.getDescendants(false);
  16847. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16848. var descendant = descendants_1[_i];
  16849. var childMesh = descendant;
  16850. childMesh.computeWorldMatrix(true);
  16851. //make sure we have the needed params to get mix and max
  16852. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16853. continue;
  16854. }
  16855. var childBoundingInfo = childMesh.getBoundingInfo();
  16856. var boundingBox = childBoundingInfo.boundingBox;
  16857. var minBox = boundingBox.minimumWorld;
  16858. var maxBox = boundingBox.maximumWorld;
  16859. BABYLON.Tools.CheckExtends(minBox, min, max);
  16860. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16861. }
  16862. }
  16863. return {
  16864. min: min,
  16865. max: max
  16866. };
  16867. };
  16868. /**
  16869. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16870. * Returns the AbstractMesh.
  16871. */
  16872. AbstractMesh.prototype._updateBoundingInfo = function () {
  16873. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16874. this._boundingInfo.update(this.worldMatrixFromCache);
  16875. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16876. return this;
  16877. };
  16878. /**
  16879. * Update a mesh's children BoundingInfo objects only.
  16880. * Returns the AbstractMesh.
  16881. */
  16882. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16883. if (!this.subMeshes) {
  16884. return this;
  16885. }
  16886. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16887. var subMesh = this.subMeshes[subIndex];
  16888. if (!subMesh.IsGlobal) {
  16889. subMesh.updateBoundingInfo(matrix);
  16890. }
  16891. }
  16892. return this;
  16893. };
  16894. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16895. // Bounding info
  16896. this._updateBoundingInfo();
  16897. };
  16898. /**
  16899. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16900. * A mesh is in the frustum if its bounding box intersects the frustum.
  16901. * Boolean returned.
  16902. */
  16903. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16904. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16905. };
  16906. /**
  16907. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16908. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16909. * Boolean returned.
  16910. */
  16911. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16912. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16913. ;
  16914. };
  16915. /**
  16916. * True if the mesh intersects another mesh or a SolidParticle object.
  16917. * 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)
  16918. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16919. * Returns a boolean.
  16920. */
  16921. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16922. if (precise === void 0) { precise = false; }
  16923. if (!this._boundingInfo || !mesh._boundingInfo) {
  16924. return false;
  16925. }
  16926. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16927. return true;
  16928. }
  16929. if (includeDescendants) {
  16930. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16931. var child = _a[_i];
  16932. if (child.intersectsMesh(mesh, precise, true)) {
  16933. return true;
  16934. }
  16935. }
  16936. }
  16937. return false;
  16938. };
  16939. /**
  16940. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16941. * Returns a boolean.
  16942. */
  16943. AbstractMesh.prototype.intersectsPoint = function (point) {
  16944. if (!this._boundingInfo) {
  16945. return false;
  16946. }
  16947. return this._boundingInfo.intersectsPoint(point);
  16948. };
  16949. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16950. return this.physicsImpostor;
  16951. };
  16952. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16953. if (camera === void 0) { camera = null; }
  16954. if (!camera) {
  16955. camera = this.getScene().activeCamera;
  16956. }
  16957. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16958. };
  16959. /**
  16960. * Returns the distance from the mesh to the active camera.
  16961. * Returns a float.
  16962. */
  16963. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16964. if (camera === void 0) { camera = null; }
  16965. if (!camera) {
  16966. camera = this.getScene().activeCamera;
  16967. }
  16968. return this.absolutePosition.subtract(camera.position).length();
  16969. };
  16970. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16971. if (!this.physicsImpostor) {
  16972. return this;
  16973. }
  16974. this.physicsImpostor.applyImpulse(force, contactPoint);
  16975. return this;
  16976. };
  16977. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16978. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16979. return this;
  16980. }
  16981. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16982. mainPivot: pivot1,
  16983. connectedPivot: pivot2,
  16984. nativeParams: options
  16985. });
  16986. return this;
  16987. };
  16988. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16989. // Collisions
  16990. /**
  16991. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16992. * Default `false`.
  16993. */
  16994. get: function () {
  16995. return this._checkCollisions;
  16996. },
  16997. set: function (collisionEnabled) {
  16998. this._checkCollisions = collisionEnabled;
  16999. if (this.getScene().workerCollisions) {
  17000. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17001. }
  17002. },
  17003. enumerable: true,
  17004. configurable: true
  17005. });
  17006. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17007. /**
  17008. * Gets Collider object used to compute collisions (not physics)
  17009. */
  17010. get: function () {
  17011. return this._collider;
  17012. },
  17013. enumerable: true,
  17014. configurable: true
  17015. });
  17016. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17017. var globalPosition = this.getAbsolutePosition();
  17018. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17019. if (!this._collider) {
  17020. this._collider = new BABYLON.Collider();
  17021. }
  17022. this._collider._radius = this.ellipsoid;
  17023. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17024. return this;
  17025. };
  17026. // Submeshes octree
  17027. /**
  17028. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17029. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17030. * Returns an Octree of submeshes.
  17031. */
  17032. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17033. if (maxCapacity === void 0) { maxCapacity = 64; }
  17034. if (maxDepth === void 0) { maxDepth = 2; }
  17035. if (!this._submeshesOctree) {
  17036. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17037. }
  17038. this.computeWorldMatrix(true);
  17039. var boundingInfo = this.getBoundingInfo();
  17040. // Update octree
  17041. var bbox = boundingInfo.boundingBox;
  17042. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17043. return this._submeshesOctree;
  17044. };
  17045. // Collisions
  17046. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17047. this._generatePointsArray();
  17048. if (!this._positions) {
  17049. return this;
  17050. }
  17051. // Transformation
  17052. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17053. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17054. subMesh._lastColliderWorldVertices = [];
  17055. subMesh._trianglePlanes = [];
  17056. var start = subMesh.verticesStart;
  17057. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17058. for (var i = start; i < end; i++) {
  17059. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17060. }
  17061. }
  17062. // Collide
  17063. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17064. if (collider.collisionFound) {
  17065. collider.collidedMesh = this;
  17066. }
  17067. return this;
  17068. };
  17069. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17070. var subMeshes;
  17071. var len;
  17072. // Octrees
  17073. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17074. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17075. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17076. len = intersections.length;
  17077. subMeshes = intersections.data;
  17078. }
  17079. else {
  17080. subMeshes = this.subMeshes;
  17081. len = subMeshes.length;
  17082. }
  17083. for (var index = 0; index < len; index++) {
  17084. var subMesh = subMeshes[index];
  17085. // Bounding test
  17086. if (len > 1 && !subMesh._checkCollision(collider))
  17087. continue;
  17088. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17089. }
  17090. return this;
  17091. };
  17092. AbstractMesh.prototype._checkCollision = function (collider) {
  17093. // Bounding box test
  17094. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17095. return this;
  17096. // Transformation matrix
  17097. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17098. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17099. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17100. return this;
  17101. };
  17102. // Picking
  17103. AbstractMesh.prototype._generatePointsArray = function () {
  17104. return false;
  17105. };
  17106. /**
  17107. * Checks if the passed Ray intersects with the mesh.
  17108. * Returns an object PickingInfo.
  17109. */
  17110. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17111. var pickingInfo = new BABYLON.PickingInfo();
  17112. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17113. return pickingInfo;
  17114. }
  17115. if (!this._generatePointsArray()) {
  17116. return pickingInfo;
  17117. }
  17118. var intersectInfo = null;
  17119. // Octrees
  17120. var subMeshes;
  17121. var len;
  17122. if (this._submeshesOctree && this.useOctreeForPicking) {
  17123. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17124. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17125. len = intersections.length;
  17126. subMeshes = intersections.data;
  17127. }
  17128. else {
  17129. subMeshes = this.subMeshes;
  17130. len = subMeshes.length;
  17131. }
  17132. for (var index = 0; index < len; index++) {
  17133. var subMesh = subMeshes[index];
  17134. // Bounding test
  17135. if (len > 1 && !subMesh.canIntersects(ray))
  17136. continue;
  17137. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17138. if (currentIntersectInfo) {
  17139. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17140. intersectInfo = currentIntersectInfo;
  17141. intersectInfo.subMeshId = index;
  17142. if (fastCheck) {
  17143. break;
  17144. }
  17145. }
  17146. }
  17147. }
  17148. if (intersectInfo) {
  17149. // Get picked point
  17150. var world = this.getWorldMatrix();
  17151. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17152. var direction = ray.direction.clone();
  17153. direction = direction.scale(intersectInfo.distance);
  17154. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17155. var pickedPoint = worldOrigin.add(worldDirection);
  17156. // Return result
  17157. pickingInfo.hit = true;
  17158. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17159. pickingInfo.pickedPoint = pickedPoint;
  17160. pickingInfo.pickedMesh = this;
  17161. pickingInfo.bu = intersectInfo.bu || 0;
  17162. pickingInfo.bv = intersectInfo.bv || 0;
  17163. pickingInfo.faceId = intersectInfo.faceId;
  17164. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17165. return pickingInfo;
  17166. }
  17167. return pickingInfo;
  17168. };
  17169. /**
  17170. * Clones the mesh, used by the class Mesh.
  17171. * Just returns `null` for an AbstractMesh.
  17172. */
  17173. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17174. return null;
  17175. };
  17176. /**
  17177. * Disposes all the mesh submeshes.
  17178. * Returns the AbstractMesh.
  17179. */
  17180. AbstractMesh.prototype.releaseSubMeshes = function () {
  17181. if (this.subMeshes) {
  17182. while (this.subMeshes.length) {
  17183. this.subMeshes[0].dispose();
  17184. }
  17185. }
  17186. else {
  17187. this.subMeshes = new Array();
  17188. }
  17189. return this;
  17190. };
  17191. /**
  17192. * Disposes the AbstractMesh.
  17193. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17194. * Returns nothing.
  17195. */
  17196. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17197. var _this = this;
  17198. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17199. var index;
  17200. // Action manager
  17201. if (this.actionManager !== undefined && this.actionManager !== null) {
  17202. this.actionManager.dispose();
  17203. this.actionManager = null;
  17204. }
  17205. // Skeleton
  17206. this.skeleton = null;
  17207. // Physics
  17208. if (this.physicsImpostor) {
  17209. this.physicsImpostor.dispose();
  17210. }
  17211. // Intersections in progress
  17212. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17213. var other = this._intersectionsInProgress[index];
  17214. var pos = other._intersectionsInProgress.indexOf(this);
  17215. other._intersectionsInProgress.splice(pos, 1);
  17216. }
  17217. this._intersectionsInProgress = [];
  17218. // Lights
  17219. var lights = this.getScene().lights;
  17220. lights.forEach(function (light) {
  17221. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17222. if (meshIndex !== -1) {
  17223. light.includedOnlyMeshes.splice(meshIndex, 1);
  17224. }
  17225. meshIndex = light.excludedMeshes.indexOf(_this);
  17226. if (meshIndex !== -1) {
  17227. light.excludedMeshes.splice(meshIndex, 1);
  17228. }
  17229. // Shadow generators
  17230. var generator = light.getShadowGenerator();
  17231. if (generator) {
  17232. var shadowMap = generator.getShadowMap();
  17233. if (shadowMap && shadowMap.renderList) {
  17234. meshIndex = shadowMap.renderList.indexOf(_this);
  17235. if (meshIndex !== -1) {
  17236. shadowMap.renderList.splice(meshIndex, 1);
  17237. }
  17238. }
  17239. }
  17240. });
  17241. // Edges
  17242. if (this._edgesRenderer) {
  17243. this._edgesRenderer.dispose();
  17244. this._edgesRenderer = null;
  17245. }
  17246. // SubMeshes
  17247. if (this.getClassName() !== "InstancedMesh") {
  17248. this.releaseSubMeshes();
  17249. }
  17250. // Octree
  17251. var sceneOctree = this.getScene().selectionOctree;
  17252. if (sceneOctree !== undefined && sceneOctree !== null) {
  17253. var index = sceneOctree.dynamicContent.indexOf(this);
  17254. if (index !== -1) {
  17255. sceneOctree.dynamicContent.splice(index, 1);
  17256. }
  17257. }
  17258. // Query
  17259. var engine = this.getScene().getEngine();
  17260. if (this._occlusionQuery) {
  17261. this._isOcclusionQueryInProgress = false;
  17262. engine.deleteQuery(this._occlusionQuery);
  17263. this._occlusionQuery = null;
  17264. }
  17265. // Engine
  17266. engine.wipeCaches();
  17267. // Remove from scene
  17268. this.getScene().removeMesh(this);
  17269. if (disposeMaterialAndTextures) {
  17270. if (this.material) {
  17271. this.material.dispose(false, true);
  17272. }
  17273. }
  17274. if (!doNotRecurse) {
  17275. // Particles
  17276. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17277. if (this.getScene().particleSystems[index].emitter === this) {
  17278. this.getScene().particleSystems[index].dispose();
  17279. index--;
  17280. }
  17281. }
  17282. }
  17283. // facet data
  17284. if (this._facetDataEnabled) {
  17285. this.disableFacetData();
  17286. }
  17287. this.onAfterWorldMatrixUpdateObservable.clear();
  17288. this.onCollideObservable.clear();
  17289. this.onCollisionPositionChangeObservable.clear();
  17290. this._isDisposed = true;
  17291. _super.prototype.dispose.call(this, doNotRecurse);
  17292. };
  17293. /**
  17294. * Adds the passed mesh as a child to the current mesh.
  17295. * Returns the AbstractMesh.
  17296. */
  17297. AbstractMesh.prototype.addChild = function (mesh) {
  17298. mesh.setParent(this);
  17299. return this;
  17300. };
  17301. /**
  17302. * Removes the passed mesh from the current mesh children list.
  17303. * Returns the AbstractMesh.
  17304. */
  17305. AbstractMesh.prototype.removeChild = function (mesh) {
  17306. mesh.setParent(null);
  17307. return this;
  17308. };
  17309. // Facet data
  17310. /**
  17311. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17312. * Returns the AbstractMesh.
  17313. */
  17314. AbstractMesh.prototype._initFacetData = function () {
  17315. if (!this._facetNormals) {
  17316. this._facetNormals = new Array();
  17317. }
  17318. if (!this._facetPositions) {
  17319. this._facetPositions = new Array();
  17320. }
  17321. if (!this._facetPartitioning) {
  17322. this._facetPartitioning = new Array();
  17323. }
  17324. this._facetNb = (this.getIndices().length / 3) | 0;
  17325. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17326. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17327. for (var f = 0; f < this._facetNb; f++) {
  17328. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17329. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17330. }
  17331. this._facetDataEnabled = true;
  17332. return this;
  17333. };
  17334. /**
  17335. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17336. * This method can be called within the render loop.
  17337. * 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.
  17338. * Returns the AbstractMesh.
  17339. */
  17340. AbstractMesh.prototype.updateFacetData = function () {
  17341. if (!this._facetDataEnabled) {
  17342. this._initFacetData();
  17343. }
  17344. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17345. var indices = this.getIndices();
  17346. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17347. var bInfo = this.getBoundingInfo();
  17348. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  17349. // init arrays, matrix and sort function on first call
  17350. this._facetDepthSortEnabled = true;
  17351. if (indices instanceof Uint16Array) {
  17352. this._depthSortedIndices = new Uint16Array(indices);
  17353. }
  17354. else if (indices instanceof Uint32Array) {
  17355. this._depthSortedIndices = new Uint32Array(indices);
  17356. }
  17357. else {
  17358. var needs32bits = false;
  17359. for (var i = 0; i < indices.length; i++) {
  17360. if (indices[i] > 65535) {
  17361. needs32bits = true;
  17362. break;
  17363. }
  17364. }
  17365. if (needs32bits) {
  17366. this._depthSortedIndices = new Uint32Array(indices);
  17367. }
  17368. else {
  17369. this._depthSortedIndices = new Uint16Array(indices);
  17370. }
  17371. }
  17372. this._facetDepthSortFunction = function (f1, f2) {
  17373. return (f2.sqDistance - f1.sqDistance);
  17374. };
  17375. if (!this._facetDepthSortFrom) {
  17376. var camera = this.getScene().activeCamera;
  17377. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  17378. }
  17379. this._depthSortedFacets = [];
  17380. for (var f = 0; f < this._facetNb; f++) {
  17381. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  17382. this._depthSortedFacets.push(depthSortedFacet);
  17383. }
  17384. this._invertedMatrix = BABYLON.Matrix.Identity();
  17385. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  17386. }
  17387. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  17388. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  17389. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  17390. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  17391. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  17392. this._subDiv.max = this._partitioningSubdivisions;
  17393. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  17394. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  17395. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  17396. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  17397. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  17398. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  17399. // set the parameters for ComputeNormals()
  17400. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  17401. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  17402. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  17403. this._facetParameters.bInfo = bInfo;
  17404. this._facetParameters.bbSize = this._bbSize;
  17405. this._facetParameters.subDiv = this._subDiv;
  17406. this._facetParameters.ratio = this.partitioningBBoxRatio;
  17407. this._facetParameters.depthSort = this._facetDepthSort;
  17408. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17409. this.computeWorldMatrix(true);
  17410. this._worldMatrix.invertToRef(this._invertedMatrix);
  17411. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  17412. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  17413. }
  17414. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  17415. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  17416. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17417. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  17418. var l = (this._depthSortedIndices.length / 3) | 0;
  17419. for (var f = 0; f < l; f++) {
  17420. var sind = this._depthSortedFacets[f].ind;
  17421. this._depthSortedIndices[f * 3] = indices[sind];
  17422. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  17423. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  17424. }
  17425. this.updateIndices(this._depthSortedIndices);
  17426. }
  17427. return this;
  17428. };
  17429. /**
  17430. * Returns the facetLocalNormals array.
  17431. * The normals are expressed in the mesh local space.
  17432. */
  17433. AbstractMesh.prototype.getFacetLocalNormals = function () {
  17434. if (!this._facetNormals) {
  17435. this.updateFacetData();
  17436. }
  17437. return this._facetNormals;
  17438. };
  17439. /**
  17440. * Returns the facetLocalPositions array.
  17441. * The facet positions are expressed in the mesh local space.
  17442. */
  17443. AbstractMesh.prototype.getFacetLocalPositions = function () {
  17444. if (!this._facetPositions) {
  17445. this.updateFacetData();
  17446. }
  17447. return this._facetPositions;
  17448. };
  17449. /**
  17450. * Returns the facetLocalPartioning array.
  17451. */
  17452. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  17453. if (!this._facetPartitioning) {
  17454. this.updateFacetData();
  17455. }
  17456. return this._facetPartitioning;
  17457. };
  17458. /**
  17459. * Returns the i-th facet position in the world system.
  17460. * This method allocates a new Vector3 per call.
  17461. */
  17462. AbstractMesh.prototype.getFacetPosition = function (i) {
  17463. var pos = BABYLON.Vector3.Zero();
  17464. this.getFacetPositionToRef(i, pos);
  17465. return pos;
  17466. };
  17467. /**
  17468. * Sets the reference Vector3 with the i-th facet position in the world system.
  17469. * Returns the AbstractMesh.
  17470. */
  17471. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  17472. var localPos = (this.getFacetLocalPositions())[i];
  17473. var world = this.getWorldMatrix();
  17474. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  17475. return this;
  17476. };
  17477. /**
  17478. * Returns the i-th facet normal in the world system.
  17479. * This method allocates a new Vector3 per call.
  17480. */
  17481. AbstractMesh.prototype.getFacetNormal = function (i) {
  17482. var norm = BABYLON.Vector3.Zero();
  17483. this.getFacetNormalToRef(i, norm);
  17484. return norm;
  17485. };
  17486. /**
  17487. * Sets the reference Vector3 with the i-th facet normal in the world system.
  17488. * Returns the AbstractMesh.
  17489. */
  17490. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  17491. var localNorm = (this.getFacetLocalNormals())[i];
  17492. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  17493. return this;
  17494. };
  17495. /**
  17496. * 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).
  17497. */
  17498. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  17499. var bInfo = this.getBoundingInfo();
  17500. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  17501. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  17502. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  17503. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  17504. return null;
  17505. }
  17506. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  17507. };
  17508. /**
  17509. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  17510. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  17511. * 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.
  17512. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17513. * 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.
  17514. */
  17515. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  17516. if (checkFace === void 0) { checkFace = false; }
  17517. if (facing === void 0) { facing = true; }
  17518. var world = this.getWorldMatrix();
  17519. var invMat = BABYLON.Tmp.Matrix[5];
  17520. world.invertToRef(invMat);
  17521. var invVect = BABYLON.Tmp.Vector3[8];
  17522. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  17523. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  17524. if (projected) {
  17525. // tranform the local computed projected vector to world coordinates
  17526. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  17527. }
  17528. return closest;
  17529. };
  17530. /**
  17531. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  17532. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  17533. * 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.
  17534. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17535. * 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.
  17536. */
  17537. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  17538. if (checkFace === void 0) { checkFace = false; }
  17539. if (facing === void 0) { facing = true; }
  17540. var closest = null;
  17541. var tmpx = 0.0;
  17542. var tmpy = 0.0;
  17543. var tmpz = 0.0;
  17544. var d = 0.0; // tmp dot facet normal * facet position
  17545. var t0 = 0.0;
  17546. var projx = 0.0;
  17547. var projy = 0.0;
  17548. var projz = 0.0;
  17549. // Get all the facets in the same partitioning block than (x, y, z)
  17550. var facetPositions = this.getFacetLocalPositions();
  17551. var facetNormals = this.getFacetLocalNormals();
  17552. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  17553. if (!facetsInBlock) {
  17554. return null;
  17555. }
  17556. // Get the closest facet to (x, y, z)
  17557. var shortest = Number.MAX_VALUE; // init distance vars
  17558. var tmpDistance = shortest;
  17559. var fib; // current facet in the block
  17560. var norm; // current facet normal
  17561. var p0; // current facet barycenter position
  17562. // loop on all the facets in the current partitioning block
  17563. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  17564. fib = facetsInBlock[idx];
  17565. norm = facetNormals[fib];
  17566. p0 = facetPositions[fib];
  17567. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  17568. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  17569. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  17570. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  17571. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  17572. projx = x + norm.x * t0;
  17573. projy = y + norm.y * t0;
  17574. projz = z + norm.z * t0;
  17575. tmpx = projx - x;
  17576. tmpy = projy - y;
  17577. tmpz = projz - z;
  17578. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  17579. if (tmpDistance < shortest) {
  17580. shortest = tmpDistance;
  17581. closest = fib;
  17582. if (projected) {
  17583. projected.x = projx;
  17584. projected.y = projy;
  17585. projected.z = projz;
  17586. }
  17587. }
  17588. }
  17589. }
  17590. return closest;
  17591. };
  17592. /**
  17593. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  17594. */
  17595. AbstractMesh.prototype.getFacetDataParameters = function () {
  17596. return this._facetParameters;
  17597. };
  17598. /**
  17599. * Disables the feature FacetData and frees the related memory.
  17600. * Returns the AbstractMesh.
  17601. */
  17602. AbstractMesh.prototype.disableFacetData = function () {
  17603. if (this._facetDataEnabled) {
  17604. this._facetDataEnabled = false;
  17605. this._facetPositions = new Array();
  17606. this._facetNormals = new Array();
  17607. this._facetPartitioning = new Array();
  17608. this._facetParameters = null;
  17609. this._depthSortedIndices = new Uint32Array(0);
  17610. }
  17611. return this;
  17612. };
  17613. /**
  17614. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  17615. * Returns the mesh.
  17616. */
  17617. AbstractMesh.prototype.updateIndices = function (indices) {
  17618. return this;
  17619. };
  17620. /**
  17621. * The mesh Geometry. Actually used by the Mesh object.
  17622. * Returns a blank geometry object.
  17623. */
  17624. /**
  17625. * Creates new normals data for the mesh.
  17626. * @param updatable.
  17627. */
  17628. AbstractMesh.prototype.createNormals = function (updatable) {
  17629. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17630. var indices = this.getIndices();
  17631. var normals;
  17632. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17633. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17634. }
  17635. else {
  17636. normals = [];
  17637. }
  17638. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17639. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17640. };
  17641. /**
  17642. * Align the mesh with a normal.
  17643. * Returns the mesh.
  17644. */
  17645. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17646. if (!upDirection) {
  17647. upDirection = BABYLON.Axis.Y;
  17648. }
  17649. var axisX = BABYLON.Tmp.Vector3[0];
  17650. var axisZ = BABYLON.Tmp.Vector3[1];
  17651. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17652. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17653. if (this.rotationQuaternion) {
  17654. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17655. }
  17656. else {
  17657. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17658. }
  17659. return this;
  17660. };
  17661. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17662. var engine = this.getEngine();
  17663. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17664. this._isOccluded = false;
  17665. return;
  17666. }
  17667. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17668. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17669. if (isOcclusionQueryAvailable) {
  17670. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17671. this._isOcclusionQueryInProgress = false;
  17672. this._occlusionInternalRetryCounter = 0;
  17673. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17674. }
  17675. else {
  17676. this._occlusionInternalRetryCounter++;
  17677. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17678. this._isOcclusionQueryInProgress = false;
  17679. this._occlusionInternalRetryCounter = 0;
  17680. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17681. // if strict continue the last state of the object.
  17682. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17683. }
  17684. else {
  17685. return;
  17686. }
  17687. }
  17688. }
  17689. var scene = this.getScene();
  17690. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17691. if (!this._occlusionQuery) {
  17692. this._occlusionQuery = engine.createQuery();
  17693. }
  17694. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17695. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17696. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17697. this._isOcclusionQueryInProgress = true;
  17698. };
  17699. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17700. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17701. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17702. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17703. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17704. return AbstractMesh;
  17705. }(BABYLON.TransformNode));
  17706. BABYLON.AbstractMesh = AbstractMesh;
  17707. })(BABYLON || (BABYLON = {}));
  17708. //# sourceMappingURL=babylon.abstractMesh.js.map
  17709. var BABYLON;
  17710. (function (BABYLON) {
  17711. /**
  17712. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  17713. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  17714. * 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.
  17715. */
  17716. var Light = /** @class */ (function (_super) {
  17717. __extends(Light, _super);
  17718. /**
  17719. * Creates a Light object in the scene.
  17720. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17721. * @param name The firendly name of the light
  17722. * @param scene The scene the light belongs too
  17723. */
  17724. function Light(name, scene) {
  17725. var _this = _super.call(this, name, scene) || this;
  17726. /**
  17727. * Diffuse gives the basic color to an object.
  17728. */
  17729. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17730. /**
  17731. * Specular produces a highlight color on an object.
  17732. * Note: This is note affecting PBR materials.
  17733. */
  17734. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17735. /**
  17736. * Strength of the light.
  17737. * Note: By default it is define in the framework own unit.
  17738. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  17739. */
  17740. _this.intensity = 1.0;
  17741. /**
  17742. * Defines how far from the source the light is impacting in scene units.
  17743. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  17744. */
  17745. _this.range = Number.MAX_VALUE;
  17746. /**
  17747. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17748. * of light.
  17749. */
  17750. _this._photometricScale = 1.0;
  17751. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17752. _this._radius = 0.00001;
  17753. /**
  17754. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  17755. * exceeding the number allowed of the materials.
  17756. */
  17757. _this.renderPriority = 0;
  17758. /**
  17759. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17760. * the current shadow generator.
  17761. */
  17762. _this.shadowEnabled = true;
  17763. _this._excludeWithLayerMask = 0;
  17764. _this._includeOnlyWithLayerMask = 0;
  17765. _this._lightmapMode = 0;
  17766. /**
  17767. * @ignore Internal use only.
  17768. */
  17769. _this._excludedMeshesIds = new Array();
  17770. /**
  17771. * @ignore Internal use only.
  17772. */
  17773. _this._includedOnlyMeshesIds = new Array();
  17774. _this.getScene().addLight(_this);
  17775. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17776. _this._buildUniformLayout();
  17777. _this.includedOnlyMeshes = new Array();
  17778. _this.excludedMeshes = new Array();
  17779. _this._resyncMeshes();
  17780. return _this;
  17781. }
  17782. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17783. /**
  17784. * If every light affecting the material is in this lightmapMode,
  17785. * material.lightmapTexture adds or multiplies
  17786. * (depends on material.useLightmapAsShadowmap)
  17787. * after every other light calculations.
  17788. */
  17789. get: function () {
  17790. return Light._LIGHTMAP_DEFAULT;
  17791. },
  17792. enumerable: true,
  17793. configurable: true
  17794. });
  17795. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17796. /**
  17797. * material.lightmapTexture as only diffuse lighting from this light
  17798. * adds only specular lighting from this light
  17799. * adds dynamic shadows
  17800. */
  17801. get: function () {
  17802. return Light._LIGHTMAP_SPECULAR;
  17803. },
  17804. enumerable: true,
  17805. configurable: true
  17806. });
  17807. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17808. /**
  17809. * material.lightmapTexture as only lighting
  17810. * no light calculation from this light
  17811. * only adds dynamic shadows from this light
  17812. */
  17813. get: function () {
  17814. return Light._LIGHTMAP_SHADOWSONLY;
  17815. },
  17816. enumerable: true,
  17817. configurable: true
  17818. });
  17819. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17820. /**
  17821. * Each light type uses the default quantity according to its type:
  17822. * point/spot lights use luminous intensity
  17823. * directional lights use illuminance
  17824. */
  17825. get: function () {
  17826. return Light._INTENSITYMODE_AUTOMATIC;
  17827. },
  17828. enumerable: true,
  17829. configurable: true
  17830. });
  17831. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17832. /**
  17833. * lumen (lm)
  17834. */
  17835. get: function () {
  17836. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17837. },
  17838. enumerable: true,
  17839. configurable: true
  17840. });
  17841. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17842. /**
  17843. * candela (lm/sr)
  17844. */
  17845. get: function () {
  17846. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17847. },
  17848. enumerable: true,
  17849. configurable: true
  17850. });
  17851. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17852. /**
  17853. * lux (lm/m^2)
  17854. */
  17855. get: function () {
  17856. return Light._INTENSITYMODE_ILLUMINANCE;
  17857. },
  17858. enumerable: true,
  17859. configurable: true
  17860. });
  17861. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17862. /**
  17863. * nit (cd/m^2)
  17864. */
  17865. get: function () {
  17866. return Light._INTENSITYMODE_LUMINANCE;
  17867. },
  17868. enumerable: true,
  17869. configurable: true
  17870. });
  17871. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17872. /**
  17873. * Light type const id of the point light.
  17874. */
  17875. get: function () {
  17876. return Light._LIGHTTYPEID_POINTLIGHT;
  17877. },
  17878. enumerable: true,
  17879. configurable: true
  17880. });
  17881. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17882. /**
  17883. * Light type const id of the directional light.
  17884. */
  17885. get: function () {
  17886. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17887. },
  17888. enumerable: true,
  17889. configurable: true
  17890. });
  17891. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17892. /**
  17893. * Light type const id of the spot light.
  17894. */
  17895. get: function () {
  17896. return Light._LIGHTTYPEID_SPOTLIGHT;
  17897. },
  17898. enumerable: true,
  17899. configurable: true
  17900. });
  17901. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17902. /**
  17903. * Light type const id of the hemispheric light.
  17904. */
  17905. get: function () {
  17906. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17907. },
  17908. enumerable: true,
  17909. configurable: true
  17910. });
  17911. Object.defineProperty(Light.prototype, "intensityMode", {
  17912. /**
  17913. * Gets the photometric scale used to interpret the intensity.
  17914. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17915. */
  17916. get: function () {
  17917. return this._intensityMode;
  17918. },
  17919. /**
  17920. * Sets the photometric scale used to interpret the intensity.
  17921. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17922. */
  17923. set: function (value) {
  17924. this._intensityMode = value;
  17925. this._computePhotometricScale();
  17926. },
  17927. enumerable: true,
  17928. configurable: true
  17929. });
  17930. ;
  17931. ;
  17932. Object.defineProperty(Light.prototype, "radius", {
  17933. /**
  17934. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17935. */
  17936. get: function () {
  17937. return this._radius;
  17938. },
  17939. /**
  17940. * sets the light radius used by PBR Materials to simulate soft area lights.
  17941. */
  17942. set: function (value) {
  17943. this._radius = value;
  17944. this._computePhotometricScale();
  17945. },
  17946. enumerable: true,
  17947. configurable: true
  17948. });
  17949. ;
  17950. ;
  17951. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17952. /**
  17953. * Gets the only meshes impacted by this light.
  17954. */
  17955. get: function () {
  17956. return this._includedOnlyMeshes;
  17957. },
  17958. /**
  17959. * Sets the only meshes impacted by this light.
  17960. */
  17961. set: function (value) {
  17962. this._includedOnlyMeshes = value;
  17963. this._hookArrayForIncludedOnly(value);
  17964. },
  17965. enumerable: true,
  17966. configurable: true
  17967. });
  17968. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17969. /**
  17970. * Gets the meshes not impacted by this light.
  17971. */
  17972. get: function () {
  17973. return this._excludedMeshes;
  17974. },
  17975. /**
  17976. * Sets the meshes not impacted by this light.
  17977. */
  17978. set: function (value) {
  17979. this._excludedMeshes = value;
  17980. this._hookArrayForExcluded(value);
  17981. },
  17982. enumerable: true,
  17983. configurable: true
  17984. });
  17985. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17986. /**
  17987. * Gets the layer id use to find what meshes are not impacted by the light.
  17988. * Inactive if 0
  17989. */
  17990. get: function () {
  17991. return this._excludeWithLayerMask;
  17992. },
  17993. /**
  17994. * Sets the layer id use to find what meshes are not impacted by the light.
  17995. * Inactive if 0
  17996. */
  17997. set: function (value) {
  17998. this._excludeWithLayerMask = value;
  17999. this._resyncMeshes();
  18000. },
  18001. enumerable: true,
  18002. configurable: true
  18003. });
  18004. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18005. /**
  18006. * Gets the layer id use to find what meshes are impacted by the light.
  18007. * Inactive if 0
  18008. */
  18009. get: function () {
  18010. return this._includeOnlyWithLayerMask;
  18011. },
  18012. /**
  18013. * Sets the layer id use to find what meshes are impacted by the light.
  18014. * Inactive if 0
  18015. */
  18016. set: function (value) {
  18017. this._includeOnlyWithLayerMask = value;
  18018. this._resyncMeshes();
  18019. },
  18020. enumerable: true,
  18021. configurable: true
  18022. });
  18023. Object.defineProperty(Light.prototype, "lightmapMode", {
  18024. /**
  18025. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18026. */
  18027. get: function () {
  18028. return this._lightmapMode;
  18029. },
  18030. /**
  18031. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18032. */
  18033. set: function (value) {
  18034. if (this._lightmapMode === value) {
  18035. return;
  18036. }
  18037. this._lightmapMode = value;
  18038. this._markMeshesAsLightDirty();
  18039. },
  18040. enumerable: true,
  18041. configurable: true
  18042. });
  18043. /**
  18044. * Returns the string "Light".
  18045. * @returns the class name
  18046. */
  18047. Light.prototype.getClassName = function () {
  18048. return "Light";
  18049. };
  18050. /**
  18051. * Converts the light information to a readable string for debug purpose.
  18052. * @param fullDetails Supports for multiple levels of logging within scene loading
  18053. * @returns the human readable light info
  18054. */
  18055. Light.prototype.toString = function (fullDetails) {
  18056. var ret = "Name: " + this.name;
  18057. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18058. if (this.animations) {
  18059. for (var i = 0; i < this.animations.length; i++) {
  18060. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18061. }
  18062. }
  18063. if (fullDetails) {
  18064. }
  18065. return ret;
  18066. };
  18067. /**
  18068. * Set the enabled state of this node.
  18069. * @param value - the new enabled state
  18070. * @see isEnabled
  18071. */
  18072. Light.prototype.setEnabled = function (value) {
  18073. _super.prototype.setEnabled.call(this, value);
  18074. this._resyncMeshes();
  18075. };
  18076. /**
  18077. * Returns the Light associated shadow generator if any.
  18078. * @return the associated shadow generator.
  18079. */
  18080. Light.prototype.getShadowGenerator = function () {
  18081. return this._shadowGenerator;
  18082. };
  18083. /**
  18084. * Returns a Vector3, the absolute light position in the World.
  18085. * @returns the world space position of the light
  18086. */
  18087. Light.prototype.getAbsolutePosition = function () {
  18088. return BABYLON.Vector3.Zero();
  18089. };
  18090. /**
  18091. * Specifies if the light will affect the passed mesh.
  18092. * @param mesh The mesh to test against the light
  18093. * @return true the mesh is affected otherwise, false.
  18094. */
  18095. Light.prototype.canAffectMesh = function (mesh) {
  18096. if (!mesh) {
  18097. return true;
  18098. }
  18099. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18100. return false;
  18101. }
  18102. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18103. return false;
  18104. }
  18105. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18106. return false;
  18107. }
  18108. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18109. return false;
  18110. }
  18111. return true;
  18112. };
  18113. /**
  18114. * Computes and Returns the light World matrix.
  18115. * @returns the world matrix
  18116. */
  18117. Light.prototype.getWorldMatrix = function () {
  18118. this._currentRenderId = this.getScene().getRenderId();
  18119. var worldMatrix = this._getWorldMatrix();
  18120. if (this.parent && this.parent.getWorldMatrix) {
  18121. if (!this._parentedWorldMatrix) {
  18122. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18123. }
  18124. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18125. this._markSyncedWithParent();
  18126. return this._parentedWorldMatrix;
  18127. }
  18128. return worldMatrix;
  18129. };
  18130. /**
  18131. * Sort function to order lights for rendering.
  18132. * @param a First Light object to compare to second.
  18133. * @param b Second Light object to compare first.
  18134. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18135. */
  18136. Light.CompareLightsPriority = function (a, b) {
  18137. //shadow-casting lights have priority over non-shadow-casting lights
  18138. //the renderPrioirty is a secondary sort criterion
  18139. if (a.shadowEnabled !== b.shadowEnabled) {
  18140. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18141. }
  18142. return b.renderPriority - a.renderPriority;
  18143. };
  18144. /**
  18145. * Disposes the light.
  18146. */
  18147. Light.prototype.dispose = function () {
  18148. if (this._shadowGenerator) {
  18149. this._shadowGenerator.dispose();
  18150. this._shadowGenerator = null;
  18151. }
  18152. // Animations
  18153. this.getScene().stopAnimation(this);
  18154. // Remove from meshes
  18155. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18156. var mesh = _a[_i];
  18157. mesh._removeLightSource(this);
  18158. }
  18159. this._uniformBuffer.dispose();
  18160. // Remove from scene
  18161. this.getScene().removeLight(this);
  18162. _super.prototype.dispose.call(this);
  18163. };
  18164. /**
  18165. * Returns the light type ID (integer).
  18166. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18167. */
  18168. Light.prototype.getTypeID = function () {
  18169. return 0;
  18170. };
  18171. /**
  18172. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18173. * @returns the scaled intensity in intensity mode unit
  18174. */
  18175. Light.prototype.getScaledIntensity = function () {
  18176. return this._photometricScale * this.intensity;
  18177. };
  18178. /**
  18179. * Returns a new Light object, named "name", from the current one.
  18180. * @param name The name of the cloned light
  18181. * @returns the new created light
  18182. */
  18183. Light.prototype.clone = function (name) {
  18184. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18185. if (!constructor) {
  18186. return null;
  18187. }
  18188. return BABYLON.SerializationHelper.Clone(constructor, this);
  18189. };
  18190. /**
  18191. * Serializes the current light into a Serialization object.
  18192. * @returns the serialized object.
  18193. */
  18194. Light.prototype.serialize = function () {
  18195. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18196. // Type
  18197. serializationObject.type = this.getTypeID();
  18198. // Parent
  18199. if (this.parent) {
  18200. serializationObject.parentId = this.parent.id;
  18201. }
  18202. // Inclusion / exclusions
  18203. if (this.excludedMeshes.length > 0) {
  18204. serializationObject.excludedMeshesIds = [];
  18205. this.excludedMeshes.forEach(function (mesh) {
  18206. serializationObject.excludedMeshesIds.push(mesh.id);
  18207. });
  18208. }
  18209. if (this.includedOnlyMeshes.length > 0) {
  18210. serializationObject.includedOnlyMeshesIds = [];
  18211. this.includedOnlyMeshes.forEach(function (mesh) {
  18212. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18213. });
  18214. }
  18215. // Animations
  18216. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18217. serializationObject.ranges = this.serializeAnimationRanges();
  18218. return serializationObject;
  18219. };
  18220. /**
  18221. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18222. * This new light is named "name" and added to the passed scene.
  18223. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18224. * @param name The friendly name of the light
  18225. * @param scene The scene the new light will belong to
  18226. * @returns the constructor function
  18227. */
  18228. Light.GetConstructorFromName = function (type, name, scene) {
  18229. switch (type) {
  18230. case 0:
  18231. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18232. case 1:
  18233. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18234. case 2:
  18235. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18236. case 3:
  18237. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18238. }
  18239. return null;
  18240. };
  18241. /**
  18242. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18243. * @param parsedLight The JSON representation of the light
  18244. * @param scene The scene to create the parsed light in
  18245. * @returns the created light after parsing
  18246. */
  18247. Light.Parse = function (parsedLight, scene) {
  18248. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18249. if (!constructor) {
  18250. return null;
  18251. }
  18252. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18253. // Inclusion / exclusions
  18254. if (parsedLight.excludedMeshesIds) {
  18255. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18256. }
  18257. if (parsedLight.includedOnlyMeshesIds) {
  18258. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18259. }
  18260. // Parent
  18261. if (parsedLight.parentId) {
  18262. light._waitingParentId = parsedLight.parentId;
  18263. }
  18264. // Animations
  18265. if (parsedLight.animations) {
  18266. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18267. var parsedAnimation = parsedLight.animations[animationIndex];
  18268. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18269. }
  18270. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18271. }
  18272. if (parsedLight.autoAnimate) {
  18273. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18274. }
  18275. return light;
  18276. };
  18277. Light.prototype._hookArrayForExcluded = function (array) {
  18278. var _this = this;
  18279. var oldPush = array.push;
  18280. array.push = function () {
  18281. var items = [];
  18282. for (var _i = 0; _i < arguments.length; _i++) {
  18283. items[_i] = arguments[_i];
  18284. }
  18285. var result = oldPush.apply(array, items);
  18286. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18287. var item = items_1[_a];
  18288. item._resyncLighSource(_this);
  18289. }
  18290. return result;
  18291. };
  18292. var oldSplice = array.splice;
  18293. array.splice = function (index, deleteCount) {
  18294. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18295. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18296. var item = deleted_1[_i];
  18297. item._resyncLighSource(_this);
  18298. }
  18299. return deleted;
  18300. };
  18301. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18302. var item = array_1[_i];
  18303. item._resyncLighSource(this);
  18304. }
  18305. };
  18306. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18307. var _this = this;
  18308. var oldPush = array.push;
  18309. array.push = function () {
  18310. var items = [];
  18311. for (var _i = 0; _i < arguments.length; _i++) {
  18312. items[_i] = arguments[_i];
  18313. }
  18314. var result = oldPush.apply(array, items);
  18315. _this._resyncMeshes();
  18316. return result;
  18317. };
  18318. var oldSplice = array.splice;
  18319. array.splice = function (index, deleteCount) {
  18320. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18321. _this._resyncMeshes();
  18322. return deleted;
  18323. };
  18324. this._resyncMeshes();
  18325. };
  18326. Light.prototype._resyncMeshes = function () {
  18327. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18328. var mesh = _a[_i];
  18329. mesh._resyncLighSource(this);
  18330. }
  18331. };
  18332. /**
  18333. * Forces the meshes to update their light related information in their rendering used effects
  18334. * @ignore Internal Use Only
  18335. */
  18336. Light.prototype._markMeshesAsLightDirty = function () {
  18337. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18338. var mesh = _a[_i];
  18339. if (mesh._lightSources.indexOf(this) !== -1) {
  18340. mesh._markSubMeshesAsLightDirty();
  18341. }
  18342. }
  18343. };
  18344. /**
  18345. * Recomputes the cached photometric scale if needed.
  18346. */
  18347. Light.prototype._computePhotometricScale = function () {
  18348. this._photometricScale = this._getPhotometricScale();
  18349. this.getScene().resetCachedMaterial();
  18350. };
  18351. /**
  18352. * Returns the Photometric Scale according to the light type and intensity mode.
  18353. */
  18354. Light.prototype._getPhotometricScale = function () {
  18355. var photometricScale = 0.0;
  18356. var lightTypeID = this.getTypeID();
  18357. //get photometric mode
  18358. var photometricMode = this.intensityMode;
  18359. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  18360. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  18361. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  18362. }
  18363. else {
  18364. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  18365. }
  18366. }
  18367. //compute photometric scale
  18368. switch (lightTypeID) {
  18369. case Light.LIGHTTYPEID_POINTLIGHT:
  18370. case Light.LIGHTTYPEID_SPOTLIGHT:
  18371. switch (photometricMode) {
  18372. case Light.INTENSITYMODE_LUMINOUSPOWER:
  18373. photometricScale = 1.0 / (4.0 * Math.PI);
  18374. break;
  18375. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  18376. photometricScale = 1.0;
  18377. break;
  18378. case Light.INTENSITYMODE_LUMINANCE:
  18379. photometricScale = this.radius * this.radius;
  18380. break;
  18381. }
  18382. break;
  18383. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  18384. switch (photometricMode) {
  18385. case Light.INTENSITYMODE_ILLUMINANCE:
  18386. photometricScale = 1.0;
  18387. break;
  18388. case Light.INTENSITYMODE_LUMINANCE:
  18389. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  18390. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  18391. var apexAngleRadians = this.radius;
  18392. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  18393. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  18394. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  18395. photometricScale = solidAngle;
  18396. break;
  18397. }
  18398. break;
  18399. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  18400. // No fall off in hemisperic light.
  18401. photometricScale = 1.0;
  18402. break;
  18403. }
  18404. return photometricScale;
  18405. };
  18406. /**
  18407. * Reorder the light in the scene according to their defined priority.
  18408. * @ignore Internal Use Only
  18409. */
  18410. Light.prototype._reorderLightsInScene = function () {
  18411. var scene = this.getScene();
  18412. if (this._renderPriority != 0) {
  18413. scene.requireLightSorting = true;
  18414. }
  18415. this.getScene().sortLightsByPriority();
  18416. };
  18417. //lightmapMode Consts
  18418. Light._LIGHTMAP_DEFAULT = 0;
  18419. Light._LIGHTMAP_SPECULAR = 1;
  18420. Light._LIGHTMAP_SHADOWSONLY = 2;
  18421. // Intensity Mode Consts
  18422. Light._INTENSITYMODE_AUTOMATIC = 0;
  18423. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  18424. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  18425. Light._INTENSITYMODE_ILLUMINANCE = 3;
  18426. Light._INTENSITYMODE_LUMINANCE = 4;
  18427. // Light types ids const.
  18428. Light._LIGHTTYPEID_POINTLIGHT = 0;
  18429. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  18430. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  18431. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  18432. __decorate([
  18433. BABYLON.serializeAsColor3()
  18434. ], Light.prototype, "diffuse", void 0);
  18435. __decorate([
  18436. BABYLON.serializeAsColor3()
  18437. ], Light.prototype, "specular", void 0);
  18438. __decorate([
  18439. BABYLON.serialize()
  18440. ], Light.prototype, "intensity", void 0);
  18441. __decorate([
  18442. BABYLON.serialize()
  18443. ], Light.prototype, "range", void 0);
  18444. __decorate([
  18445. BABYLON.serialize()
  18446. ], Light.prototype, "intensityMode", null);
  18447. __decorate([
  18448. BABYLON.serialize()
  18449. ], Light.prototype, "radius", null);
  18450. __decorate([
  18451. BABYLON.serialize()
  18452. ], Light.prototype, "_renderPriority", void 0);
  18453. __decorate([
  18454. BABYLON.expandToProperty("_reorderLightsInScene")
  18455. ], Light.prototype, "renderPriority", void 0);
  18456. __decorate([
  18457. BABYLON.serialize()
  18458. ], Light.prototype, "shadowEnabled", void 0);
  18459. __decorate([
  18460. BABYLON.serialize("excludeWithLayerMask")
  18461. ], Light.prototype, "_excludeWithLayerMask", void 0);
  18462. __decorate([
  18463. BABYLON.serialize("includeOnlyWithLayerMask")
  18464. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  18465. __decorate([
  18466. BABYLON.serialize("lightmapMode")
  18467. ], Light.prototype, "_lightmapMode", void 0);
  18468. return Light;
  18469. }(BABYLON.Node));
  18470. BABYLON.Light = Light;
  18471. })(BABYLON || (BABYLON = {}));
  18472. //# sourceMappingURL=babylon.light.js.map
  18473. var BABYLON;
  18474. (function (BABYLON) {
  18475. var Camera = /** @class */ (function (_super) {
  18476. __extends(Camera, _super);
  18477. function Camera(name, position, scene) {
  18478. var _this = _super.call(this, name, scene) || this;
  18479. /**
  18480. * The vector the camera should consider as up.
  18481. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  18482. */
  18483. _this.upVector = BABYLON.Vector3.Up();
  18484. _this.orthoLeft = null;
  18485. _this.orthoRight = null;
  18486. _this.orthoBottom = null;
  18487. _this.orthoTop = null;
  18488. /**
  18489. * FOV is set in Radians. (default is 0.8)
  18490. */
  18491. _this.fov = 0.8;
  18492. _this.minZ = 1;
  18493. _this.maxZ = 10000.0;
  18494. _this.inertia = 0.9;
  18495. _this.mode = Camera.PERSPECTIVE_CAMERA;
  18496. _this.isIntermediate = false;
  18497. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  18498. /**
  18499. * Restricts the camera to viewing objects with the same layerMask.
  18500. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  18501. */
  18502. _this.layerMask = 0x0FFFFFFF;
  18503. /**
  18504. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  18505. */
  18506. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  18507. // Camera rig members
  18508. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  18509. _this._rigCameras = new Array();
  18510. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  18511. _this._skipRendering = false;
  18512. _this.customRenderTargets = new Array();
  18513. // Observables
  18514. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  18515. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  18516. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  18517. _this.onRestoreStateObservable = new BABYLON.Observable();
  18518. // Cache
  18519. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  18520. _this._projectionMatrix = new BABYLON.Matrix();
  18521. _this._doNotComputeProjectionMatrix = false;
  18522. _this._postProcesses = new Array();
  18523. _this._transformMatrix = BABYLON.Matrix.Zero();
  18524. _this._activeMeshes = new BABYLON.SmartArray(256);
  18525. _this._globalPosition = BABYLON.Vector3.Zero();
  18526. _this._refreshFrustumPlanes = true;
  18527. _this.getScene().addCamera(_this);
  18528. if (!_this.getScene().activeCamera) {
  18529. _this.getScene().activeCamera = _this;
  18530. }
  18531. _this.position = position;
  18532. return _this;
  18533. }
  18534. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  18535. get: function () {
  18536. return Camera._PERSPECTIVE_CAMERA;
  18537. },
  18538. enumerable: true,
  18539. configurable: true
  18540. });
  18541. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  18542. get: function () {
  18543. return Camera._ORTHOGRAPHIC_CAMERA;
  18544. },
  18545. enumerable: true,
  18546. configurable: true
  18547. });
  18548. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  18549. /**
  18550. * This is the default FOV mode for perspective cameras.
  18551. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  18552. *
  18553. */
  18554. get: function () {
  18555. return Camera._FOVMODE_VERTICAL_FIXED;
  18556. },
  18557. enumerable: true,
  18558. configurable: true
  18559. });
  18560. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  18561. /**
  18562. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  18563. *
  18564. */
  18565. get: function () {
  18566. return Camera._FOVMODE_HORIZONTAL_FIXED;
  18567. },
  18568. enumerable: true,
  18569. configurable: true
  18570. });
  18571. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  18572. get: function () {
  18573. return Camera._RIG_MODE_NONE;
  18574. },
  18575. enumerable: true,
  18576. configurable: true
  18577. });
  18578. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  18579. get: function () {
  18580. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  18581. },
  18582. enumerable: true,
  18583. configurable: true
  18584. });
  18585. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  18586. get: function () {
  18587. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  18588. },
  18589. enumerable: true,
  18590. configurable: true
  18591. });
  18592. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  18593. get: function () {
  18594. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18595. },
  18596. enumerable: true,
  18597. configurable: true
  18598. });
  18599. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  18600. get: function () {
  18601. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  18602. },
  18603. enumerable: true,
  18604. configurable: true
  18605. });
  18606. Object.defineProperty(Camera, "RIG_MODE_VR", {
  18607. get: function () {
  18608. return Camera._RIG_MODE_VR;
  18609. },
  18610. enumerable: true,
  18611. configurable: true
  18612. });
  18613. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  18614. get: function () {
  18615. return Camera._RIG_MODE_WEBVR;
  18616. },
  18617. enumerable: true,
  18618. configurable: true
  18619. });
  18620. /**
  18621. * Store current camera state (fov, position, etc..)
  18622. */
  18623. Camera.prototype.storeState = function () {
  18624. this._stateStored = true;
  18625. this._storedFov = this.fov;
  18626. return this;
  18627. };
  18628. /**
  18629. * Restores the camera state values if it has been stored. You must call storeState() first
  18630. */
  18631. Camera.prototype._restoreStateValues = function () {
  18632. if (!this._stateStored) {
  18633. return false;
  18634. }
  18635. this.fov = this._storedFov;
  18636. return true;
  18637. };
  18638. /**
  18639. * Restored camera state. You must call storeState() first
  18640. */
  18641. Camera.prototype.restoreState = function () {
  18642. if (this._restoreStateValues()) {
  18643. this.onRestoreStateObservable.notifyObservers(this);
  18644. return true;
  18645. }
  18646. return false;
  18647. };
  18648. Camera.prototype.getClassName = function () {
  18649. return "Camera";
  18650. };
  18651. /**
  18652. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18653. */
  18654. Camera.prototype.toString = function (fullDetails) {
  18655. var ret = "Name: " + this.name;
  18656. ret += ", type: " + this.getClassName();
  18657. if (this.animations) {
  18658. for (var i = 0; i < this.animations.length; i++) {
  18659. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18660. }
  18661. }
  18662. if (fullDetails) {
  18663. }
  18664. return ret;
  18665. };
  18666. Object.defineProperty(Camera.prototype, "globalPosition", {
  18667. get: function () {
  18668. return this._globalPosition;
  18669. },
  18670. enumerable: true,
  18671. configurable: true
  18672. });
  18673. Camera.prototype.getActiveMeshes = function () {
  18674. return this._activeMeshes;
  18675. };
  18676. Camera.prototype.isActiveMesh = function (mesh) {
  18677. return (this._activeMeshes.indexOf(mesh) !== -1);
  18678. };
  18679. //Cache
  18680. Camera.prototype._initCache = function () {
  18681. _super.prototype._initCache.call(this);
  18682. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18683. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18684. this._cache.mode = undefined;
  18685. this._cache.minZ = undefined;
  18686. this._cache.maxZ = undefined;
  18687. this._cache.fov = undefined;
  18688. this._cache.fovMode = undefined;
  18689. this._cache.aspectRatio = undefined;
  18690. this._cache.orthoLeft = undefined;
  18691. this._cache.orthoRight = undefined;
  18692. this._cache.orthoBottom = undefined;
  18693. this._cache.orthoTop = undefined;
  18694. this._cache.renderWidth = undefined;
  18695. this._cache.renderHeight = undefined;
  18696. };
  18697. Camera.prototype._updateCache = function (ignoreParentClass) {
  18698. if (!ignoreParentClass) {
  18699. _super.prototype._updateCache.call(this);
  18700. }
  18701. this._cache.position.copyFrom(this.position);
  18702. this._cache.upVector.copyFrom(this.upVector);
  18703. };
  18704. // Synchronized
  18705. Camera.prototype._isSynchronized = function () {
  18706. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  18707. };
  18708. Camera.prototype._isSynchronizedViewMatrix = function () {
  18709. if (!_super.prototype._isSynchronized.call(this))
  18710. return false;
  18711. return this._cache.position.equals(this.position)
  18712. && this._cache.upVector.equals(this.upVector)
  18713. && this.isSynchronizedWithParent();
  18714. };
  18715. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  18716. var check = this._cache.mode === this.mode
  18717. && this._cache.minZ === this.minZ
  18718. && this._cache.maxZ === this.maxZ;
  18719. if (!check) {
  18720. return false;
  18721. }
  18722. var engine = this.getEngine();
  18723. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18724. check = this._cache.fov === this.fov
  18725. && this._cache.fovMode === this.fovMode
  18726. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18727. }
  18728. else {
  18729. check = this._cache.orthoLeft === this.orthoLeft
  18730. && this._cache.orthoRight === this.orthoRight
  18731. && this._cache.orthoBottom === this.orthoBottom
  18732. && this._cache.orthoTop === this.orthoTop
  18733. && this._cache.renderWidth === engine.getRenderWidth()
  18734. && this._cache.renderHeight === engine.getRenderHeight();
  18735. }
  18736. return check;
  18737. };
  18738. // Controls
  18739. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18740. };
  18741. Camera.prototype.detachControl = function (element) {
  18742. };
  18743. Camera.prototype.update = function () {
  18744. this._checkInputs();
  18745. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18746. this._updateRigCameras();
  18747. }
  18748. };
  18749. Camera.prototype._checkInputs = function () {
  18750. this.onAfterCheckInputsObservable.notifyObservers(this);
  18751. };
  18752. Object.defineProperty(Camera.prototype, "rigCameras", {
  18753. get: function () {
  18754. return this._rigCameras;
  18755. },
  18756. enumerable: true,
  18757. configurable: true
  18758. });
  18759. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18760. get: function () {
  18761. return this._rigPostProcess;
  18762. },
  18763. enumerable: true,
  18764. configurable: true
  18765. });
  18766. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18767. // invalidate framebuffer
  18768. if (this._postProcesses.length > 0) {
  18769. this._postProcesses[0].markTextureDirty();
  18770. }
  18771. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18772. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18773. var cam = this._rigCameras[i];
  18774. var rigPostProcess = cam._rigPostProcess;
  18775. // for VR rig, there does not have to be a post process
  18776. if (rigPostProcess) {
  18777. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18778. if (isPass) {
  18779. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18780. cam.isIntermediate = this._postProcesses.length === 0;
  18781. }
  18782. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18783. rigPostProcess.markTextureDirty();
  18784. }
  18785. else {
  18786. cam._postProcesses = this._postProcesses.slice(0);
  18787. }
  18788. }
  18789. };
  18790. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18791. if (insertAt === void 0) { insertAt = null; }
  18792. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18793. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18794. return 0;
  18795. }
  18796. if (insertAt == null || insertAt < 0) {
  18797. this._postProcesses.push(postProcess);
  18798. }
  18799. else {
  18800. this._postProcesses.splice(insertAt, 0, postProcess);
  18801. }
  18802. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18803. return this._postProcesses.indexOf(postProcess);
  18804. };
  18805. Camera.prototype.detachPostProcess = function (postProcess) {
  18806. var idx = this._postProcesses.indexOf(postProcess);
  18807. if (idx !== -1) {
  18808. this._postProcesses.splice(idx, 1);
  18809. }
  18810. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18811. };
  18812. Camera.prototype.getWorldMatrix = function () {
  18813. if (!this._worldMatrix) {
  18814. this._worldMatrix = BABYLON.Matrix.Identity();
  18815. }
  18816. var viewMatrix = this.getViewMatrix();
  18817. viewMatrix.invertToRef(this._worldMatrix);
  18818. return this._worldMatrix;
  18819. };
  18820. Camera.prototype._getViewMatrix = function () {
  18821. return BABYLON.Matrix.Identity();
  18822. };
  18823. Camera.prototype.getViewMatrix = function (force) {
  18824. if (!force && this._isSynchronizedViewMatrix()) {
  18825. return this._computedViewMatrix;
  18826. }
  18827. this.updateCache();
  18828. this._computedViewMatrix = this._getViewMatrix();
  18829. this._currentRenderId = this.getScene().getRenderId();
  18830. this._refreshFrustumPlanes = true;
  18831. if (!this.parent || !this.parent.getWorldMatrix) {
  18832. this._globalPosition.copyFrom(this.position);
  18833. }
  18834. else {
  18835. if (!this._worldMatrix) {
  18836. this._worldMatrix = BABYLON.Matrix.Identity();
  18837. }
  18838. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18839. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18840. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18841. this._computedViewMatrix.invert();
  18842. this._markSyncedWithParent();
  18843. }
  18844. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18845. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18846. }
  18847. this.onViewMatrixChangedObservable.notifyObservers(this);
  18848. return this._computedViewMatrix;
  18849. };
  18850. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18851. this._doNotComputeProjectionMatrix = true;
  18852. if (projection !== undefined) {
  18853. this._projectionMatrix = projection;
  18854. }
  18855. };
  18856. ;
  18857. Camera.prototype.unfreezeProjectionMatrix = function () {
  18858. this._doNotComputeProjectionMatrix = false;
  18859. };
  18860. ;
  18861. Camera.prototype.getProjectionMatrix = function (force) {
  18862. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18863. return this._projectionMatrix;
  18864. }
  18865. // Cache
  18866. this._cache.mode = this.mode;
  18867. this._cache.minZ = this.minZ;
  18868. this._cache.maxZ = this.maxZ;
  18869. // Matrix
  18870. this._refreshFrustumPlanes = true;
  18871. var engine = this.getEngine();
  18872. var scene = this.getScene();
  18873. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18874. this._cache.fov = this.fov;
  18875. this._cache.fovMode = this.fovMode;
  18876. this._cache.aspectRatio = engine.getAspectRatio(this);
  18877. if (this.minZ <= 0) {
  18878. this.minZ = 0.1;
  18879. }
  18880. if (scene.useRightHandedSystem) {
  18881. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18882. }
  18883. else {
  18884. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18885. }
  18886. }
  18887. else {
  18888. var halfWidth = engine.getRenderWidth() / 2.0;
  18889. var halfHeight = engine.getRenderHeight() / 2.0;
  18890. if (scene.useRightHandedSystem) {
  18891. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18892. }
  18893. else {
  18894. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18895. }
  18896. this._cache.orthoLeft = this.orthoLeft;
  18897. this._cache.orthoRight = this.orthoRight;
  18898. this._cache.orthoBottom = this.orthoBottom;
  18899. this._cache.orthoTop = this.orthoTop;
  18900. this._cache.renderWidth = engine.getRenderWidth();
  18901. this._cache.renderHeight = engine.getRenderHeight();
  18902. }
  18903. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18904. return this._projectionMatrix;
  18905. };
  18906. Camera.prototype.getTranformationMatrix = function () {
  18907. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18908. return this._transformMatrix;
  18909. };
  18910. Camera.prototype.updateFrustumPlanes = function () {
  18911. if (!this._refreshFrustumPlanes) {
  18912. return;
  18913. }
  18914. this.getTranformationMatrix();
  18915. if (!this._frustumPlanes) {
  18916. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18917. }
  18918. else {
  18919. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18920. }
  18921. this._refreshFrustumPlanes = false;
  18922. };
  18923. Camera.prototype.isInFrustum = function (target) {
  18924. this.updateFrustumPlanes();
  18925. return target.isInFrustum(this._frustumPlanes);
  18926. };
  18927. Camera.prototype.isCompletelyInFrustum = function (target) {
  18928. this.updateFrustumPlanes();
  18929. return target.isCompletelyInFrustum(this._frustumPlanes);
  18930. };
  18931. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18932. if (length === void 0) { length = 100; }
  18933. if (!transform) {
  18934. transform = this.getWorldMatrix();
  18935. }
  18936. if (!origin) {
  18937. origin = this.position;
  18938. }
  18939. var forward = new BABYLON.Vector3(0, 0, 1);
  18940. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18941. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18942. return new BABYLON.Ray(origin, direction, length);
  18943. };
  18944. Camera.prototype.dispose = function () {
  18945. // Observables
  18946. this.onViewMatrixChangedObservable.clear();
  18947. this.onProjectionMatrixChangedObservable.clear();
  18948. this.onAfterCheckInputsObservable.clear();
  18949. this.onRestoreStateObservable.clear();
  18950. // Inputs
  18951. if (this.inputs) {
  18952. this.inputs.clear();
  18953. }
  18954. // Animations
  18955. this.getScene().stopAnimation(this);
  18956. // Remove from scene
  18957. this.getScene().removeCamera(this);
  18958. while (this._rigCameras.length > 0) {
  18959. var camera = this._rigCameras.pop();
  18960. if (camera) {
  18961. camera.dispose();
  18962. }
  18963. }
  18964. // Postprocesses
  18965. if (this._rigPostProcess) {
  18966. this._rigPostProcess.dispose(this);
  18967. this._rigPostProcess = null;
  18968. this._postProcesses = [];
  18969. }
  18970. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18971. this._rigPostProcess = null;
  18972. this._postProcesses = [];
  18973. }
  18974. else {
  18975. var i = this._postProcesses.length;
  18976. while (--i >= 0) {
  18977. this._postProcesses[i].dispose(this);
  18978. }
  18979. }
  18980. // Render targets
  18981. var i = this.customRenderTargets.length;
  18982. while (--i >= 0) {
  18983. this.customRenderTargets[i].dispose();
  18984. }
  18985. this.customRenderTargets = [];
  18986. // Active Meshes
  18987. this._activeMeshes.dispose();
  18988. _super.prototype.dispose.call(this);
  18989. };
  18990. Object.defineProperty(Camera.prototype, "leftCamera", {
  18991. // ---- Camera rigs section ----
  18992. get: function () {
  18993. if (this._rigCameras.length < 1) {
  18994. return null;
  18995. }
  18996. return this._rigCameras[0];
  18997. },
  18998. enumerable: true,
  18999. configurable: true
  19000. });
  19001. Object.defineProperty(Camera.prototype, "rightCamera", {
  19002. get: function () {
  19003. if (this._rigCameras.length < 2) {
  19004. return null;
  19005. }
  19006. return this._rigCameras[1];
  19007. },
  19008. enumerable: true,
  19009. configurable: true
  19010. });
  19011. Camera.prototype.getLeftTarget = function () {
  19012. if (this._rigCameras.length < 1) {
  19013. return null;
  19014. }
  19015. return this._rigCameras[0].getTarget();
  19016. };
  19017. Camera.prototype.getRightTarget = function () {
  19018. if (this._rigCameras.length < 2) {
  19019. return null;
  19020. }
  19021. return this._rigCameras[1].getTarget();
  19022. };
  19023. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19024. if (this.cameraRigMode === mode) {
  19025. return;
  19026. }
  19027. while (this._rigCameras.length > 0) {
  19028. var camera = this._rigCameras.pop();
  19029. if (camera) {
  19030. camera.dispose();
  19031. }
  19032. }
  19033. this.cameraRigMode = mode;
  19034. this._cameraRigParams = {};
  19035. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19036. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19037. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19038. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19039. // create the rig cameras, unless none
  19040. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19041. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19042. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19043. if (leftCamera && rightCamera) {
  19044. this._rigCameras.push(leftCamera);
  19045. this._rigCameras.push(rightCamera);
  19046. }
  19047. }
  19048. switch (this.cameraRigMode) {
  19049. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19050. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19051. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19052. break;
  19053. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19054. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19055. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19056. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19057. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19058. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19059. break;
  19060. case Camera.RIG_MODE_VR:
  19061. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19062. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19063. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19064. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19065. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19066. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19067. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19068. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19069. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19070. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19071. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19072. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19073. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19074. if (metrics.compensateDistortion) {
  19075. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19076. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19077. }
  19078. break;
  19079. case Camera.RIG_MODE_WEBVR:
  19080. if (rigParams.vrDisplay) {
  19081. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19082. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19083. //Left eye
  19084. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19085. this._rigCameras[0].setCameraRigParameter("left", true);
  19086. //leaving this for future reference
  19087. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19088. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19089. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19090. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19091. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19092. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19093. this._rigCameras[0].parent = this;
  19094. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19095. //Right eye
  19096. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19097. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19098. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19099. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19100. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19101. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19102. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19103. this._rigCameras[1].parent = this;
  19104. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19105. if (Camera.UseAlternateWebVRRendering) {
  19106. this._rigCameras[1]._skipRendering = true;
  19107. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19108. }
  19109. }
  19110. break;
  19111. }
  19112. this._cascadePostProcessesToRigCams();
  19113. this.update();
  19114. };
  19115. Camera.prototype._getVRProjectionMatrix = function () {
  19116. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19117. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19118. return this._projectionMatrix;
  19119. };
  19120. Camera.prototype._updateCameraRotationMatrix = function () {
  19121. //Here for WebVR
  19122. };
  19123. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19124. //Here for WebVR
  19125. };
  19126. /**
  19127. * This function MUST be overwritten by the different WebVR cameras available.
  19128. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19129. */
  19130. Camera.prototype._getWebVRProjectionMatrix = function () {
  19131. return BABYLON.Matrix.Identity();
  19132. };
  19133. /**
  19134. * This function MUST be overwritten by the different WebVR cameras available.
  19135. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19136. */
  19137. Camera.prototype._getWebVRViewMatrix = function () {
  19138. return BABYLON.Matrix.Identity();
  19139. };
  19140. Camera.prototype.setCameraRigParameter = function (name, value) {
  19141. if (!this._cameraRigParams) {
  19142. this._cameraRigParams = {};
  19143. }
  19144. this._cameraRigParams[name] = value;
  19145. //provisionnally:
  19146. if (name === "interaxialDistance") {
  19147. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19148. }
  19149. };
  19150. /**
  19151. * needs to be overridden by children so sub has required properties to be copied
  19152. */
  19153. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19154. return null;
  19155. };
  19156. /**
  19157. * May need to be overridden by children
  19158. */
  19159. Camera.prototype._updateRigCameras = function () {
  19160. for (var i = 0; i < this._rigCameras.length; i++) {
  19161. this._rigCameras[i].minZ = this.minZ;
  19162. this._rigCameras[i].maxZ = this.maxZ;
  19163. this._rigCameras[i].fov = this.fov;
  19164. }
  19165. // only update viewport when ANAGLYPH
  19166. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19167. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19168. }
  19169. };
  19170. Camera.prototype._setupInputs = function () {
  19171. };
  19172. Camera.prototype.serialize = function () {
  19173. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19174. // Type
  19175. serializationObject.type = this.getClassName();
  19176. // Parent
  19177. if (this.parent) {
  19178. serializationObject.parentId = this.parent.id;
  19179. }
  19180. if (this.inputs) {
  19181. this.inputs.serialize(serializationObject);
  19182. }
  19183. // Animations
  19184. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19185. serializationObject.ranges = this.serializeAnimationRanges();
  19186. return serializationObject;
  19187. };
  19188. Camera.prototype.clone = function (name) {
  19189. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19190. };
  19191. Camera.prototype.getDirection = function (localAxis) {
  19192. var result = BABYLON.Vector3.Zero();
  19193. this.getDirectionToRef(localAxis, result);
  19194. return result;
  19195. };
  19196. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19197. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19198. };
  19199. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19200. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19201. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19202. switch (type) {
  19203. case "ArcRotateCamera":
  19204. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19205. case "DeviceOrientationCamera":
  19206. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19207. case "FollowCamera":
  19208. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19209. case "ArcFollowCamera":
  19210. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19211. case "GamepadCamera":
  19212. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19213. case "TouchCamera":
  19214. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19215. case "VirtualJoysticksCamera":
  19216. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19217. case "WebVRFreeCamera":
  19218. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19219. case "WebVRGamepadCamera":
  19220. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19221. case "VRDeviceOrientationFreeCamera":
  19222. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19223. case "VRDeviceOrientationGamepadCamera":
  19224. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19225. case "AnaglyphArcRotateCamera":
  19226. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19227. case "AnaglyphFreeCamera":
  19228. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19229. case "AnaglyphGamepadCamera":
  19230. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19231. case "AnaglyphUniversalCamera":
  19232. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19233. case "StereoscopicArcRotateCamera":
  19234. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19235. case "StereoscopicFreeCamera":
  19236. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19237. case "StereoscopicGamepadCamera":
  19238. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19239. case "StereoscopicUniversalCamera":
  19240. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19241. case "FreeCamera":// Forcing Universal here
  19242. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19243. default:// Universal Camera is the default value
  19244. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19245. }
  19246. };
  19247. Camera.prototype.computeWorldMatrix = function () {
  19248. return this.getWorldMatrix();
  19249. };
  19250. Camera.Parse = function (parsedCamera, scene) {
  19251. var type = parsedCamera.type;
  19252. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19253. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19254. // Parent
  19255. if (parsedCamera.parentId) {
  19256. camera._waitingParentId = parsedCamera.parentId;
  19257. }
  19258. //If camera has an input manager, let it parse inputs settings
  19259. if (camera.inputs) {
  19260. camera.inputs.parse(parsedCamera);
  19261. camera._setupInputs();
  19262. }
  19263. if (camera.setPosition) {
  19264. camera.position.copyFromFloats(0, 0, 0);
  19265. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19266. }
  19267. // Target
  19268. if (parsedCamera.target) {
  19269. if (camera.setTarget) {
  19270. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19271. }
  19272. }
  19273. // Apply 3d rig, when found
  19274. if (parsedCamera.cameraRigMode) {
  19275. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19276. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19277. }
  19278. // Animations
  19279. if (parsedCamera.animations) {
  19280. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19281. var parsedAnimation = parsedCamera.animations[animationIndex];
  19282. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19283. }
  19284. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19285. }
  19286. if (parsedCamera.autoAnimate) {
  19287. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19288. }
  19289. return camera;
  19290. };
  19291. // Statics
  19292. Camera._PERSPECTIVE_CAMERA = 0;
  19293. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19294. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19295. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19296. Camera._RIG_MODE_NONE = 0;
  19297. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19298. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19299. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19300. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19301. Camera._RIG_MODE_VR = 20;
  19302. Camera._RIG_MODE_WEBVR = 21;
  19303. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19304. Camera.UseAlternateWebVRRendering = false;
  19305. __decorate([
  19306. BABYLON.serializeAsVector3()
  19307. ], Camera.prototype, "position", void 0);
  19308. __decorate([
  19309. BABYLON.serializeAsVector3()
  19310. ], Camera.prototype, "upVector", void 0);
  19311. __decorate([
  19312. BABYLON.serialize()
  19313. ], Camera.prototype, "orthoLeft", void 0);
  19314. __decorate([
  19315. BABYLON.serialize()
  19316. ], Camera.prototype, "orthoRight", void 0);
  19317. __decorate([
  19318. BABYLON.serialize()
  19319. ], Camera.prototype, "orthoBottom", void 0);
  19320. __decorate([
  19321. BABYLON.serialize()
  19322. ], Camera.prototype, "orthoTop", void 0);
  19323. __decorate([
  19324. BABYLON.serialize()
  19325. ], Camera.prototype, "fov", void 0);
  19326. __decorate([
  19327. BABYLON.serialize()
  19328. ], Camera.prototype, "minZ", void 0);
  19329. __decorate([
  19330. BABYLON.serialize()
  19331. ], Camera.prototype, "maxZ", void 0);
  19332. __decorate([
  19333. BABYLON.serialize()
  19334. ], Camera.prototype, "inertia", void 0);
  19335. __decorate([
  19336. BABYLON.serialize()
  19337. ], Camera.prototype, "mode", void 0);
  19338. __decorate([
  19339. BABYLON.serialize()
  19340. ], Camera.prototype, "layerMask", void 0);
  19341. __decorate([
  19342. BABYLON.serialize()
  19343. ], Camera.prototype, "fovMode", void 0);
  19344. __decorate([
  19345. BABYLON.serialize()
  19346. ], Camera.prototype, "cameraRigMode", void 0);
  19347. __decorate([
  19348. BABYLON.serialize()
  19349. ], Camera.prototype, "interaxialDistance", void 0);
  19350. __decorate([
  19351. BABYLON.serialize()
  19352. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  19353. return Camera;
  19354. }(BABYLON.Node));
  19355. BABYLON.Camera = Camera;
  19356. })(BABYLON || (BABYLON = {}));
  19357. //# sourceMappingURL=babylon.camera.js.map
  19358. var BABYLON;
  19359. (function (BABYLON) {
  19360. var RenderingManager = /** @class */ (function () {
  19361. function RenderingManager(scene) {
  19362. this._renderingGroups = new Array();
  19363. this._autoClearDepthStencil = {};
  19364. this._customOpaqueSortCompareFn = {};
  19365. this._customAlphaTestSortCompareFn = {};
  19366. this._customTransparentSortCompareFn = {};
  19367. this._renderinGroupInfo = null;
  19368. this._scene = scene;
  19369. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19370. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19371. }
  19372. }
  19373. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19374. if (depth === void 0) { depth = true; }
  19375. if (stencil === void 0) { stencil = true; }
  19376. if (this._depthStencilBufferAlreadyCleaned) {
  19377. return;
  19378. }
  19379. this._scene.getEngine().clear(null, false, depth, stencil);
  19380. this._depthStencilBufferAlreadyCleaned = true;
  19381. };
  19382. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19383. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19384. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19385. var info = null;
  19386. if (observable) {
  19387. if (!this._renderinGroupInfo) {
  19388. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19389. }
  19390. info = this._renderinGroupInfo;
  19391. info.scene = this._scene;
  19392. info.camera = this._scene.activeCamera;
  19393. }
  19394. // Dispatch sprites
  19395. if (renderSprites) {
  19396. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19397. var manager = this._scene.spriteManagers[index];
  19398. this.dispatchSprites(manager);
  19399. }
  19400. }
  19401. // Render
  19402. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19403. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  19404. var renderingGroup = this._renderingGroups[index];
  19405. if (!renderingGroup && !observable)
  19406. continue;
  19407. var renderingGroupMask = 0;
  19408. // Fire PRECLEAR stage
  19409. if (observable && info) {
  19410. renderingGroupMask = Math.pow(2, index);
  19411. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  19412. info.renderingGroupId = index;
  19413. observable.notifyObservers(info, renderingGroupMask);
  19414. }
  19415. // Clear depth/stencil if needed
  19416. if (RenderingManager.AUTOCLEAR) {
  19417. var autoClear = this._autoClearDepthStencil[index];
  19418. if (autoClear && autoClear.autoClear) {
  19419. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  19420. }
  19421. }
  19422. if (observable && info) {
  19423. // Fire PREOPAQUE stage
  19424. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  19425. observable.notifyObservers(info, renderingGroupMask);
  19426. // Fire PRETRANSPARENT stage
  19427. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  19428. observable.notifyObservers(info, renderingGroupMask);
  19429. }
  19430. if (renderingGroup)
  19431. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  19432. // Fire POSTTRANSPARENT stage
  19433. if (observable && info) {
  19434. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  19435. observable.notifyObservers(info, renderingGroupMask);
  19436. }
  19437. }
  19438. };
  19439. RenderingManager.prototype.reset = function () {
  19440. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19441. var renderingGroup = this._renderingGroups[index];
  19442. if (renderingGroup) {
  19443. renderingGroup.prepare();
  19444. }
  19445. }
  19446. };
  19447. RenderingManager.prototype.dispose = function () {
  19448. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19449. var renderingGroup = this._renderingGroups[index];
  19450. if (renderingGroup) {
  19451. renderingGroup.dispose();
  19452. }
  19453. }
  19454. this._renderingGroups.length = 0;
  19455. };
  19456. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  19457. if (this._renderingGroups[renderingGroupId] === undefined) {
  19458. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  19459. }
  19460. };
  19461. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  19462. var renderingGroupId = spriteManager.renderingGroupId || 0;
  19463. this._prepareRenderingGroup(renderingGroupId);
  19464. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  19465. };
  19466. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  19467. var renderingGroupId = particleSystem.renderingGroupId || 0;
  19468. this._prepareRenderingGroup(renderingGroupId);
  19469. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  19470. };
  19471. /**
  19472. * @param subMesh The submesh to dispatch
  19473. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19474. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19475. */
  19476. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  19477. if (mesh === undefined) {
  19478. mesh = subMesh.getMesh();
  19479. }
  19480. var renderingGroupId = mesh.renderingGroupId || 0;
  19481. this._prepareRenderingGroup(renderingGroupId);
  19482. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  19483. };
  19484. /**
  19485. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19486. * This allowed control for front to back rendering or reversly depending of the special needs.
  19487. *
  19488. * @param renderingGroupId The rendering group id corresponding to its index
  19489. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19490. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19491. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19492. */
  19493. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19494. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19495. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19496. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19497. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  19498. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  19499. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  19500. if (this._renderingGroups[renderingGroupId]) {
  19501. var group = this._renderingGroups[renderingGroupId];
  19502. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19503. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19504. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19505. }
  19506. };
  19507. /**
  19508. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19509. *
  19510. * @param renderingGroupId The rendering group id corresponding to its index
  19511. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19512. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19513. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19514. */
  19515. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19516. if (depth === void 0) { depth = true; }
  19517. if (stencil === void 0) { stencil = true; }
  19518. this._autoClearDepthStencil[renderingGroupId] = {
  19519. autoClear: autoClearDepthStencil,
  19520. depth: depth,
  19521. stencil: stencil
  19522. };
  19523. };
  19524. /**
  19525. * The max id used for rendering groups (not included)
  19526. */
  19527. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19528. /**
  19529. * The min id used for rendering groups (included)
  19530. */
  19531. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19532. /**
  19533. * Used to globally prevent autoclearing scenes.
  19534. */
  19535. RenderingManager.AUTOCLEAR = true;
  19536. return RenderingManager;
  19537. }());
  19538. BABYLON.RenderingManager = RenderingManager;
  19539. })(BABYLON || (BABYLON = {}));
  19540. //# sourceMappingURL=babylon.renderingManager.js.map
  19541. var BABYLON;
  19542. (function (BABYLON) {
  19543. var RenderingGroup = /** @class */ (function () {
  19544. /**
  19545. * Creates a new rendering group.
  19546. * @param index The rendering group index
  19547. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19548. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19549. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19550. */
  19551. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19552. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19553. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19554. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19555. this.index = index;
  19556. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19557. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19558. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19559. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  19560. this._particleSystems = new BABYLON.SmartArray(256);
  19561. this._spriteManagers = new BABYLON.SmartArray(256);
  19562. this._edgesRenderers = new BABYLON.SmartArray(16);
  19563. this._scene = scene;
  19564. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19565. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19566. this.transparentSortCompareFn = transparentSortCompareFn;
  19567. }
  19568. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19569. /**
  19570. * Set the opaque sort comparison function.
  19571. * If null the sub meshes will be render in the order they were created
  19572. */
  19573. set: function (value) {
  19574. this._opaqueSortCompareFn = value;
  19575. if (value) {
  19576. this._renderOpaque = this.renderOpaqueSorted;
  19577. }
  19578. else {
  19579. this._renderOpaque = RenderingGroup.renderUnsorted;
  19580. }
  19581. },
  19582. enumerable: true,
  19583. configurable: true
  19584. });
  19585. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19586. /**
  19587. * Set the alpha test sort comparison function.
  19588. * If null the sub meshes will be render in the order they were created
  19589. */
  19590. set: function (value) {
  19591. this._alphaTestSortCompareFn = value;
  19592. if (value) {
  19593. this._renderAlphaTest = this.renderAlphaTestSorted;
  19594. }
  19595. else {
  19596. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19597. }
  19598. },
  19599. enumerable: true,
  19600. configurable: true
  19601. });
  19602. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19603. /**
  19604. * Set the transparent sort comparison function.
  19605. * If null the sub meshes will be render in the order they were created
  19606. */
  19607. set: function (value) {
  19608. if (value) {
  19609. this._transparentSortCompareFn = value;
  19610. }
  19611. else {
  19612. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19613. }
  19614. this._renderTransparent = this.renderTransparentSorted;
  19615. },
  19616. enumerable: true,
  19617. configurable: true
  19618. });
  19619. /**
  19620. * Render all the sub meshes contained in the group.
  19621. * @param customRenderFunction Used to override the default render behaviour of the group.
  19622. * @returns true if rendered some submeshes.
  19623. */
  19624. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19625. if (customRenderFunction) {
  19626. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  19627. return;
  19628. }
  19629. var engine = this._scene.getEngine();
  19630. // Depth only
  19631. if (this._depthOnlySubMeshes.length !== 0) {
  19632. engine.setColorWrite(false);
  19633. this._renderAlphaTest(this._depthOnlySubMeshes);
  19634. engine.setColorWrite(true);
  19635. }
  19636. // Opaque
  19637. if (this._opaqueSubMeshes.length !== 0) {
  19638. this._renderOpaque(this._opaqueSubMeshes);
  19639. }
  19640. // Alpha test
  19641. if (this._alphaTestSubMeshes.length !== 0) {
  19642. this._renderAlphaTest(this._alphaTestSubMeshes);
  19643. }
  19644. var stencilState = engine.getStencilBuffer();
  19645. engine.setStencilBuffer(false);
  19646. // Sprites
  19647. if (renderSprites) {
  19648. this._renderSprites();
  19649. }
  19650. // Particles
  19651. if (renderParticles) {
  19652. this._renderParticles(activeMeshes);
  19653. }
  19654. if (this.onBeforeTransparentRendering) {
  19655. this.onBeforeTransparentRendering();
  19656. }
  19657. // Transparent
  19658. if (this._transparentSubMeshes.length !== 0) {
  19659. this._renderTransparent(this._transparentSubMeshes);
  19660. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19661. }
  19662. // Set back stencil to false in case it changes before the edge renderer.
  19663. engine.setStencilBuffer(false);
  19664. // Edges
  19665. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19666. this._edgesRenderers.data[edgesRendererIndex].render();
  19667. }
  19668. // Restore Stencil state.
  19669. engine.setStencilBuffer(stencilState);
  19670. };
  19671. /**
  19672. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19673. * @param subMeshes The submeshes to render
  19674. */
  19675. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19676. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  19677. };
  19678. /**
  19679. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19680. * @param subMeshes The submeshes to render
  19681. */
  19682. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19683. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  19684. };
  19685. /**
  19686. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19687. * @param subMeshes The submeshes to render
  19688. */
  19689. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19690. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  19691. };
  19692. /**
  19693. * Renders the submeshes in a specified order.
  19694. * @param subMeshes The submeshes to sort before render
  19695. * @param sortCompareFn The comparison function use to sort
  19696. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19697. * @param transparent Specifies to activate blending if true
  19698. */
  19699. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  19700. var subIndex = 0;
  19701. var subMesh;
  19702. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  19703. for (; subIndex < subMeshes.length; subIndex++) {
  19704. subMesh = subMeshes.data[subIndex];
  19705. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19706. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19707. }
  19708. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19709. if (sortCompareFn) {
  19710. sortedArray.sort(sortCompareFn);
  19711. }
  19712. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19713. subMesh = sortedArray[subIndex];
  19714. if (transparent) {
  19715. var material = subMesh.getMaterial();
  19716. if (material && material.needDepthPrePass) {
  19717. var engine = material.getScene().getEngine();
  19718. engine.setColorWrite(false);
  19719. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19720. subMesh.render(false);
  19721. engine.setColorWrite(true);
  19722. }
  19723. }
  19724. subMesh.render(transparent);
  19725. }
  19726. };
  19727. /**
  19728. * Renders the submeshes in the order they were dispatched (no sort applied).
  19729. * @param subMeshes The submeshes to render
  19730. */
  19731. RenderingGroup.renderUnsorted = function (subMeshes) {
  19732. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19733. var submesh = subMeshes.data[subIndex];
  19734. submesh.render(false);
  19735. }
  19736. };
  19737. /**
  19738. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19739. * are rendered back to front if in the same alpha index.
  19740. *
  19741. * @param a The first submesh
  19742. * @param b The second submesh
  19743. * @returns The result of the comparison
  19744. */
  19745. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19746. // Alpha index first
  19747. if (a._alphaIndex > b._alphaIndex) {
  19748. return 1;
  19749. }
  19750. if (a._alphaIndex < b._alphaIndex) {
  19751. return -1;
  19752. }
  19753. // Then distance to camera
  19754. return RenderingGroup.backToFrontSortCompare(a, b);
  19755. };
  19756. /**
  19757. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19758. * are rendered back to front.
  19759. *
  19760. * @param a The first submesh
  19761. * @param b The second submesh
  19762. * @returns The result of the comparison
  19763. */
  19764. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19765. // Then distance to camera
  19766. if (a._distanceToCamera < b._distanceToCamera) {
  19767. return 1;
  19768. }
  19769. if (a._distanceToCamera > b._distanceToCamera) {
  19770. return -1;
  19771. }
  19772. return 0;
  19773. };
  19774. /**
  19775. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19776. * are rendered front to back (prevent overdraw).
  19777. *
  19778. * @param a The first submesh
  19779. * @param b The second submesh
  19780. * @returns The result of the comparison
  19781. */
  19782. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19783. // Then distance to camera
  19784. if (a._distanceToCamera < b._distanceToCamera) {
  19785. return -1;
  19786. }
  19787. if (a._distanceToCamera > b._distanceToCamera) {
  19788. return 1;
  19789. }
  19790. return 0;
  19791. };
  19792. /**
  19793. * Resets the different lists of submeshes to prepare a new frame.
  19794. */
  19795. RenderingGroup.prototype.prepare = function () {
  19796. this._opaqueSubMeshes.reset();
  19797. this._transparentSubMeshes.reset();
  19798. this._alphaTestSubMeshes.reset();
  19799. this._depthOnlySubMeshes.reset();
  19800. this._particleSystems.reset();
  19801. this._spriteManagers.reset();
  19802. this._edgesRenderers.reset();
  19803. };
  19804. RenderingGroup.prototype.dispose = function () {
  19805. this._opaqueSubMeshes.dispose();
  19806. this._transparentSubMeshes.dispose();
  19807. this._alphaTestSubMeshes.dispose();
  19808. this._depthOnlySubMeshes.dispose();
  19809. this._particleSystems.dispose();
  19810. this._spriteManagers.dispose();
  19811. this._edgesRenderers.dispose();
  19812. };
  19813. /**
  19814. * Inserts the submesh in its correct queue depending on its material.
  19815. * @param subMesh The submesh to dispatch
  19816. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19817. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19818. */
  19819. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19820. // Get mesh and materials if not provided
  19821. if (mesh === undefined) {
  19822. mesh = subMesh.getMesh();
  19823. }
  19824. if (material === undefined) {
  19825. material = subMesh.getMaterial();
  19826. }
  19827. if (material === null || material === undefined) {
  19828. return;
  19829. }
  19830. if (material.needAlphaBlendingForMesh(mesh)) {
  19831. this._transparentSubMeshes.push(subMesh);
  19832. }
  19833. else if (material.needAlphaTesting()) {
  19834. if (material.needDepthPrePass) {
  19835. this._depthOnlySubMeshes.push(subMesh);
  19836. }
  19837. this._alphaTestSubMeshes.push(subMesh);
  19838. }
  19839. else {
  19840. if (material.needDepthPrePass) {
  19841. this._depthOnlySubMeshes.push(subMesh);
  19842. }
  19843. this._opaqueSubMeshes.push(subMesh); // Opaque
  19844. }
  19845. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19846. this._edgesRenderers.push(mesh._edgesRenderer);
  19847. }
  19848. };
  19849. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19850. this._spriteManagers.push(spriteManager);
  19851. };
  19852. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19853. this._particleSystems.push(particleSystem);
  19854. };
  19855. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19856. if (this._particleSystems.length === 0) {
  19857. return;
  19858. }
  19859. // Particles
  19860. var activeCamera = this._scene.activeCamera;
  19861. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19862. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19863. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19864. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19865. continue;
  19866. }
  19867. var emitter = particleSystem.emitter;
  19868. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19869. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19870. }
  19871. }
  19872. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19873. };
  19874. RenderingGroup.prototype._renderSprites = function () {
  19875. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19876. return;
  19877. }
  19878. // Sprites
  19879. var activeCamera = this._scene.activeCamera;
  19880. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19881. for (var id = 0; id < this._spriteManagers.length; id++) {
  19882. var spriteManager = this._spriteManagers.data[id];
  19883. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19884. spriteManager.render();
  19885. }
  19886. }
  19887. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19888. };
  19889. return RenderingGroup;
  19890. }());
  19891. BABYLON.RenderingGroup = RenderingGroup;
  19892. })(BABYLON || (BABYLON = {}));
  19893. //# sourceMappingURL=babylon.renderingGroup.js.map
  19894. var BABYLON;
  19895. (function (BABYLON) {
  19896. var ClickInfo = /** @class */ (function () {
  19897. function ClickInfo() {
  19898. this._singleClick = false;
  19899. this._doubleClick = false;
  19900. this._hasSwiped = false;
  19901. this._ignore = false;
  19902. }
  19903. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19904. get: function () {
  19905. return this._singleClick;
  19906. },
  19907. set: function (b) {
  19908. this._singleClick = b;
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19914. get: function () {
  19915. return this._doubleClick;
  19916. },
  19917. set: function (b) {
  19918. this._doubleClick = b;
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19924. get: function () {
  19925. return this._hasSwiped;
  19926. },
  19927. set: function (b) {
  19928. this._hasSwiped = b;
  19929. },
  19930. enumerable: true,
  19931. configurable: true
  19932. });
  19933. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19934. get: function () {
  19935. return this._ignore;
  19936. },
  19937. set: function (b) {
  19938. this._ignore = b;
  19939. },
  19940. enumerable: true,
  19941. configurable: true
  19942. });
  19943. return ClickInfo;
  19944. }());
  19945. /**
  19946. * This class is used by the onRenderingGroupObservable
  19947. */
  19948. var RenderingGroupInfo = /** @class */ (function () {
  19949. function RenderingGroupInfo() {
  19950. }
  19951. /**
  19952. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19953. * This stage will be fired no matter what
  19954. */
  19955. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19956. /**
  19957. * Called before opaque object are rendered.
  19958. * This stage will be fired only if there's 3D Opaque content to render
  19959. */
  19960. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19961. /**
  19962. * Called after the opaque objects are rendered and before the transparent ones
  19963. * This stage will be fired only if there's 3D transparent content to render
  19964. */
  19965. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19966. /**
  19967. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19968. * This stage will be fired no matter what
  19969. */
  19970. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19971. return RenderingGroupInfo;
  19972. }());
  19973. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19974. /**
  19975. * Represents a scene to be rendered by the engine.
  19976. * @see http://doc.babylonjs.com/page.php?p=21911
  19977. */
  19978. var Scene = /** @class */ (function () {
  19979. /**
  19980. * @constructor
  19981. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19982. */
  19983. function Scene(engine) {
  19984. // Members
  19985. this.autoClear = true;
  19986. this.autoClearDepthAndStencil = true;
  19987. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19988. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19989. this.forceWireframe = false;
  19990. this._forcePointsCloud = false;
  19991. this.forceShowBoundingBoxes = false;
  19992. this.animationsEnabled = true;
  19993. this.useConstantAnimationDeltaTime = false;
  19994. this.constantlyUpdateMeshUnderPointer = false;
  19995. this.hoverCursor = "pointer";
  19996. this.defaultCursor = "";
  19997. /**
  19998. * This is used to call preventDefault() on pointer down
  19999. * in order to block unwanted artifacts like system double clicks
  20000. */
  20001. this.preventDefaultOnPointerDown = true;
  20002. // Metadata
  20003. this.metadata = null;
  20004. /**
  20005. * An event triggered when the scene is disposed.
  20006. * @type {BABYLON.Observable}
  20007. */
  20008. this.onDisposeObservable = new BABYLON.Observable();
  20009. /**
  20010. * An event triggered before rendering the scene (right after animations and physics)
  20011. * @type {BABYLON.Observable}
  20012. */
  20013. this.onBeforeRenderObservable = new BABYLON.Observable();
  20014. /**
  20015. * An event triggered after rendering the scene
  20016. * @type {BABYLON.Observable}
  20017. */
  20018. this.onAfterRenderObservable = new BABYLON.Observable();
  20019. /**
  20020. * An event triggered before animating the scene
  20021. * @type {BABYLON.Observable}
  20022. */
  20023. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20024. /**
  20025. * An event triggered after animations processing
  20026. * @type {BABYLON.Observable}
  20027. */
  20028. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20029. /**
  20030. * An event triggered before draw calls are ready to be sent
  20031. * @type {BABYLON.Observable}
  20032. */
  20033. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20034. /**
  20035. * An event triggered after draw calls have been sent
  20036. * @type {BABYLON.Observable}
  20037. */
  20038. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20039. /**
  20040. * An event triggered when physic simulation is about to be run
  20041. * @type {BABYLON.Observable}
  20042. */
  20043. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20044. /**
  20045. * An event triggered when physic simulation has been done
  20046. * @type {BABYLON.Observable}
  20047. */
  20048. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20049. /**
  20050. * An event triggered when the scene is ready
  20051. * @type {BABYLON.Observable}
  20052. */
  20053. this.onReadyObservable = new BABYLON.Observable();
  20054. /**
  20055. * An event triggered before rendering a camera
  20056. * @type {BABYLON.Observable}
  20057. */
  20058. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20059. /**
  20060. * An event triggered after rendering a camera
  20061. * @type {BABYLON.Observable}
  20062. */
  20063. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20064. /**
  20065. * An event triggered when active meshes evaluation is about to start
  20066. * @type {BABYLON.Observable}
  20067. */
  20068. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20069. /**
  20070. * An event triggered when active meshes evaluation is done
  20071. * @type {BABYLON.Observable}
  20072. */
  20073. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20074. /**
  20075. * An event triggered when particles rendering is about to start
  20076. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20077. * @type {BABYLON.Observable}
  20078. */
  20079. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20080. /**
  20081. * An event triggered when particles rendering is done
  20082. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20083. * @type {BABYLON.Observable}
  20084. */
  20085. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20086. /**
  20087. * An event triggered when sprites rendering is about to start
  20088. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20089. * @type {BABYLON.Observable}
  20090. */
  20091. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20092. /**
  20093. * An event triggered when sprites rendering is done
  20094. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20095. * @type {BABYLON.Observable}
  20096. */
  20097. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20098. /**
  20099. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20100. * @type {BABYLON.Observable}
  20101. */
  20102. this.onDataLoadedObservable = new BABYLON.Observable();
  20103. /**
  20104. * An event triggered when a camera is created
  20105. * @type {BABYLON.Observable}
  20106. */
  20107. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20108. /**
  20109. * An event triggered when a camera is removed
  20110. * @type {BABYLON.Observable}
  20111. */
  20112. this.onCameraRemovedObservable = new BABYLON.Observable();
  20113. /**
  20114. * An event triggered when a light is created
  20115. * @type {BABYLON.Observable}
  20116. */
  20117. this.onNewLightAddedObservable = new BABYLON.Observable();
  20118. /**
  20119. * An event triggered when a light is removed
  20120. * @type {BABYLON.Observable}
  20121. */
  20122. this.onLightRemovedObservable = new BABYLON.Observable();
  20123. /**
  20124. * An event triggered when a geometry is created
  20125. * @type {BABYLON.Observable}
  20126. */
  20127. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20128. /**
  20129. * An event triggered when a geometry is removed
  20130. * @type {BABYLON.Observable}
  20131. */
  20132. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20133. /**
  20134. * An event triggered when a transform node is created
  20135. * @type {BABYLON.Observable}
  20136. */
  20137. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20138. /**
  20139. * An event triggered when a transform node is removed
  20140. * @type {BABYLON.Observable}
  20141. */
  20142. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20143. /**
  20144. * An event triggered when a mesh is created
  20145. * @type {BABYLON.Observable}
  20146. */
  20147. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20148. /**
  20149. * An event triggered when a mesh is removed
  20150. * @type {BABYLON.Observable}
  20151. */
  20152. this.onMeshRemovedObservable = new BABYLON.Observable();
  20153. /**
  20154. * An event triggered when render targets are about to be rendered
  20155. * Can happen multiple times per frame.
  20156. * @type {BABYLON.Observable}
  20157. */
  20158. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20159. /**
  20160. * An event triggered when render targets were rendered.
  20161. * Can happen multiple times per frame.
  20162. * @type {BABYLON.Observable}
  20163. */
  20164. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20165. /**
  20166. * An event triggered before calculating deterministic simulation step
  20167. * @type {BABYLON.Observable}
  20168. */
  20169. this.onBeforeStepObservable = new BABYLON.Observable();
  20170. /**
  20171. * An event triggered after calculating deterministic simulation step
  20172. * @type {BABYLON.Observable}
  20173. */
  20174. this.onAfterStepObservable = new BABYLON.Observable();
  20175. /**
  20176. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20177. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20178. * 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)
  20179. */
  20180. this.onRenderingGroupObservable = new BABYLON.Observable();
  20181. // Animations
  20182. this.animations = [];
  20183. /**
  20184. * 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).
  20185. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20186. */
  20187. this.onPrePointerObservable = new BABYLON.Observable();
  20188. /**
  20189. * Observable event triggered each time an input event is received from the rendering canvas
  20190. */
  20191. this.onPointerObservable = new BABYLON.Observable();
  20192. this._meshPickProceed = false;
  20193. this._currentPickResult = null;
  20194. this._previousPickResult = null;
  20195. this._totalPointersPressed = 0;
  20196. this._doubleClickOccured = false;
  20197. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20198. this.cameraToUseForPointers = null;
  20199. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20200. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20201. this._startingPointerTime = 0;
  20202. this._previousStartingPointerTime = 0;
  20203. // Deterministic lockstep
  20204. this._timeAccumulator = 0;
  20205. this._currentStepId = 0;
  20206. this._currentInternalStep = 0;
  20207. // Keyboard
  20208. /**
  20209. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20210. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20211. */
  20212. this.onPreKeyboardObservable = new BABYLON.Observable();
  20213. /**
  20214. * Observable event triggered each time an keyboard event is received from the hosting window
  20215. */
  20216. this.onKeyboardObservable = new BABYLON.Observable();
  20217. // Coordinate system
  20218. /**
  20219. * use right-handed coordinate system on this scene.
  20220. * @type {boolean}
  20221. */
  20222. this._useRightHandedSystem = false;
  20223. // Fog
  20224. this._fogEnabled = true;
  20225. this._fogMode = Scene.FOGMODE_NONE;
  20226. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20227. this.fogDensity = 0.1;
  20228. this.fogStart = 0;
  20229. this.fogEnd = 1000.0;
  20230. // Lights
  20231. /**
  20232. * is shadow enabled on this scene.
  20233. * @type {boolean}
  20234. */
  20235. this._shadowsEnabled = true;
  20236. /**
  20237. * is light enabled on this scene.
  20238. * @type {boolean}
  20239. */
  20240. this._lightsEnabled = true;
  20241. /**
  20242. * All of the lights added to this scene.
  20243. * @see BABYLON.Light
  20244. * @type {BABYLON.Light[]}
  20245. */
  20246. this.lights = new Array();
  20247. // Cameras
  20248. /** All of the cameras added to this scene. */
  20249. this.cameras = new Array();
  20250. /** All of the active cameras added to this scene. */
  20251. this.activeCameras = new Array();
  20252. // Meshes
  20253. /**
  20254. * All of the tranform nodes added to this scene.
  20255. * @see BABYLON.TransformNode
  20256. * @type {BABYLON.TransformNode[]}
  20257. */
  20258. this.transformNodes = new Array();
  20259. /**
  20260. * All of the (abstract) meshes added to this scene.
  20261. * @see BABYLON.AbstractMesh
  20262. * @type {BABYLON.AbstractMesh[]}
  20263. */
  20264. this.meshes = new Array();
  20265. /**
  20266. * All of the animation groups added to this scene.
  20267. * @see BABYLON.AnimationGroup
  20268. * @type {BABYLON.AnimationGroup[]}
  20269. */
  20270. this.animationGroups = new Array();
  20271. // Geometries
  20272. this._geometries = new Array();
  20273. this.materials = new Array();
  20274. this.multiMaterials = new Array();
  20275. // Textures
  20276. this._texturesEnabled = true;
  20277. this.textures = new Array();
  20278. // Particles
  20279. this.particlesEnabled = true;
  20280. this.particleSystems = new Array();
  20281. // Sprites
  20282. this.spritesEnabled = true;
  20283. this.spriteManagers = new Array();
  20284. // Layers
  20285. this.layers = new Array();
  20286. this.highlightLayers = new Array();
  20287. // Skeletons
  20288. this._skeletonsEnabled = true;
  20289. this.skeletons = new Array();
  20290. // Morph targets
  20291. this.morphTargetManagers = new Array();
  20292. // Lens flares
  20293. this.lensFlaresEnabled = true;
  20294. this.lensFlareSystems = new Array();
  20295. // Collisions
  20296. this.collisionsEnabled = true;
  20297. /** Defines the gravity applied to this scene */
  20298. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20299. // Postprocesses
  20300. this.postProcesses = new Array();
  20301. this.postProcessesEnabled = true;
  20302. // Customs render targets
  20303. this.renderTargetsEnabled = true;
  20304. this.dumpNextRenderTargets = false;
  20305. this.customRenderTargets = new Array();
  20306. // Imported meshes
  20307. this.importedMeshesFiles = new Array();
  20308. // Probes
  20309. this.probesEnabled = true;
  20310. this.reflectionProbes = new Array();
  20311. this._actionManagers = new Array();
  20312. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20313. // Procedural textures
  20314. this.proceduralTexturesEnabled = true;
  20315. this._proceduralTextures = new Array();
  20316. this.soundTracks = new Array();
  20317. this._audioEnabled = true;
  20318. this._headphone = false;
  20319. // Performance counters
  20320. this._totalVertices = new BABYLON.PerfCounter();
  20321. this._activeIndices = new BABYLON.PerfCounter();
  20322. this._activeParticles = new BABYLON.PerfCounter();
  20323. this._activeBones = new BABYLON.PerfCounter();
  20324. this._animationTime = 0;
  20325. this.animationTimeScale = 1;
  20326. this._renderId = 0;
  20327. this._executeWhenReadyTimeoutId = -1;
  20328. this._intermediateRendering = false;
  20329. this._viewUpdateFlag = -1;
  20330. this._projectionUpdateFlag = -1;
  20331. this._alternateViewUpdateFlag = -1;
  20332. this._alternateProjectionUpdateFlag = -1;
  20333. this._toBeDisposed = new BABYLON.SmartArray(256);
  20334. this._activeRequests = new Array();
  20335. this._pendingData = new Array();
  20336. this._isDisposed = false;
  20337. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20338. this._activeMeshes = new BABYLON.SmartArray(256);
  20339. this._processedMaterials = new BABYLON.SmartArray(256);
  20340. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  20341. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20342. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  20343. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  20344. this._activeAnimatables = new Array();
  20345. this._transformMatrix = BABYLON.Matrix.Zero();
  20346. this._useAlternateCameraConfiguration = false;
  20347. this._alternateRendering = false;
  20348. this.requireLightSorting = false;
  20349. this._activeMeshesFrozen = false;
  20350. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  20351. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20352. this._engine.scenes.push(this);
  20353. this._uid = null;
  20354. this._renderingManager = new BABYLON.RenderingManager(this);
  20355. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20356. if (BABYLON.OutlineRenderer) {
  20357. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20358. }
  20359. if (BABYLON.Tools.IsWindowObjectExist()) {
  20360. this.attachControl();
  20361. }
  20362. //simplification queue
  20363. if (BABYLON.SimplificationQueue) {
  20364. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20365. }
  20366. //collision coordinator initialization. For now legacy per default.
  20367. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20368. // Uniform Buffer
  20369. this._createUbo();
  20370. // Default Image processing definition.
  20371. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  20372. }
  20373. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20374. /** The fog is deactivated */
  20375. get: function () {
  20376. return Scene._FOGMODE_NONE;
  20377. },
  20378. enumerable: true,
  20379. configurable: true
  20380. });
  20381. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20382. /** The fog density is following an exponential function */
  20383. get: function () {
  20384. return Scene._FOGMODE_EXP;
  20385. },
  20386. enumerable: true,
  20387. configurable: true
  20388. });
  20389. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20390. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  20391. get: function () {
  20392. return Scene._FOGMODE_EXP2;
  20393. },
  20394. enumerable: true,
  20395. configurable: true
  20396. });
  20397. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  20398. /** The fog density is following a linear function. */
  20399. get: function () {
  20400. return Scene._FOGMODE_LINEAR;
  20401. },
  20402. enumerable: true,
  20403. configurable: true
  20404. });
  20405. Object.defineProperty(Scene.prototype, "environmentTexture", {
  20406. /**
  20407. * Texture used in all pbr material as the reflection texture.
  20408. * As in the majority of the scene they are the same (exception for multi room and so on),
  20409. * this is easier to reference from here than from all the materials.
  20410. */
  20411. get: function () {
  20412. return this._environmentTexture;
  20413. },
  20414. /**
  20415. * Texture used in all pbr material as the reflection texture.
  20416. * As in the majority of the scene they are the same (exception for multi room and so on),
  20417. * this is easier to set here than in all the materials.
  20418. */
  20419. set: function (value) {
  20420. if (this._environmentTexture === value) {
  20421. return;
  20422. }
  20423. this._environmentTexture = value;
  20424. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20425. },
  20426. enumerable: true,
  20427. configurable: true
  20428. });
  20429. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  20430. /**
  20431. * Default image processing configuration used either in the rendering
  20432. * Forward main pass or through the imageProcessingPostProcess if present.
  20433. * As in the majority of the scene they are the same (exception for multi camera),
  20434. * this is easier to reference from here than from all the materials and post process.
  20435. *
  20436. * No setter as we it is a shared configuration, you can set the values instead.
  20437. */
  20438. get: function () {
  20439. return this._imageProcessingConfiguration;
  20440. },
  20441. enumerable: true,
  20442. configurable: true
  20443. });
  20444. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  20445. get: function () {
  20446. return this._forcePointsCloud;
  20447. },
  20448. set: function (value) {
  20449. if (this._forcePointsCloud === value) {
  20450. return;
  20451. }
  20452. this._forcePointsCloud = value;
  20453. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20454. },
  20455. enumerable: true,
  20456. configurable: true
  20457. });
  20458. Object.defineProperty(Scene.prototype, "onDispose", {
  20459. /** A function to be executed when this scene is disposed. */
  20460. set: function (callback) {
  20461. if (this._onDisposeObserver) {
  20462. this.onDisposeObservable.remove(this._onDisposeObserver);
  20463. }
  20464. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20465. },
  20466. enumerable: true,
  20467. configurable: true
  20468. });
  20469. Object.defineProperty(Scene.prototype, "beforeRender", {
  20470. /** A function to be executed before rendering this scene */
  20471. set: function (callback) {
  20472. if (this._onBeforeRenderObserver) {
  20473. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  20474. }
  20475. if (callback) {
  20476. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  20477. }
  20478. },
  20479. enumerable: true,
  20480. configurable: true
  20481. });
  20482. Object.defineProperty(Scene.prototype, "afterRender", {
  20483. /** A function to be executed after rendering this scene */
  20484. set: function (callback) {
  20485. if (this._onAfterRenderObserver) {
  20486. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  20487. }
  20488. if (callback) {
  20489. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  20490. }
  20491. },
  20492. enumerable: true,
  20493. configurable: true
  20494. });
  20495. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  20496. set: function (callback) {
  20497. if (this._onBeforeCameraRenderObserver) {
  20498. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  20499. }
  20500. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  20501. },
  20502. enumerable: true,
  20503. configurable: true
  20504. });
  20505. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20506. set: function (callback) {
  20507. if (this._onAfterCameraRenderObserver) {
  20508. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20509. }
  20510. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20511. },
  20512. enumerable: true,
  20513. configurable: true
  20514. });
  20515. Object.defineProperty(Scene.prototype, "gamepadManager", {
  20516. get: function () {
  20517. if (!this._gamepadManager) {
  20518. this._gamepadManager = new BABYLON.GamepadManager(this);
  20519. }
  20520. return this._gamepadManager;
  20521. },
  20522. enumerable: true,
  20523. configurable: true
  20524. });
  20525. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20526. get: function () {
  20527. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20528. },
  20529. enumerable: true,
  20530. configurable: true
  20531. });
  20532. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  20533. get: function () {
  20534. return this._useRightHandedSystem;
  20535. },
  20536. set: function (value) {
  20537. if (this._useRightHandedSystem === value) {
  20538. return;
  20539. }
  20540. this._useRightHandedSystem = value;
  20541. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20542. },
  20543. enumerable: true,
  20544. configurable: true
  20545. });
  20546. Scene.prototype.setStepId = function (newStepId) {
  20547. this._currentStepId = newStepId;
  20548. };
  20549. ;
  20550. Scene.prototype.getStepId = function () {
  20551. return this._currentStepId;
  20552. };
  20553. ;
  20554. Scene.prototype.getInternalStep = function () {
  20555. return this._currentInternalStep;
  20556. };
  20557. ;
  20558. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20559. get: function () {
  20560. return this._fogEnabled;
  20561. },
  20562. /**
  20563. * is fog enabled on this scene.
  20564. */
  20565. set: function (value) {
  20566. if (this._fogEnabled === value) {
  20567. return;
  20568. }
  20569. this._fogEnabled = value;
  20570. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20571. },
  20572. enumerable: true,
  20573. configurable: true
  20574. });
  20575. Object.defineProperty(Scene.prototype, "fogMode", {
  20576. get: function () {
  20577. return this._fogMode;
  20578. },
  20579. set: function (value) {
  20580. if (this._fogMode === value) {
  20581. return;
  20582. }
  20583. this._fogMode = value;
  20584. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20585. },
  20586. enumerable: true,
  20587. configurable: true
  20588. });
  20589. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20590. get: function () {
  20591. return this._shadowsEnabled;
  20592. },
  20593. set: function (value) {
  20594. if (this._shadowsEnabled === value) {
  20595. return;
  20596. }
  20597. this._shadowsEnabled = value;
  20598. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20599. },
  20600. enumerable: true,
  20601. configurable: true
  20602. });
  20603. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20604. get: function () {
  20605. return this._lightsEnabled;
  20606. },
  20607. set: function (value) {
  20608. if (this._lightsEnabled === value) {
  20609. return;
  20610. }
  20611. this._lightsEnabled = value;
  20612. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20613. },
  20614. enumerable: true,
  20615. configurable: true
  20616. });
  20617. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20618. /** The default material used on meshes when no material is affected */
  20619. get: function () {
  20620. if (!this._defaultMaterial) {
  20621. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20622. }
  20623. return this._defaultMaterial;
  20624. },
  20625. /** The default material used on meshes when no material is affected */
  20626. set: function (value) {
  20627. this._defaultMaterial = value;
  20628. },
  20629. enumerable: true,
  20630. configurable: true
  20631. });
  20632. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20633. get: function () {
  20634. return this._texturesEnabled;
  20635. },
  20636. set: function (value) {
  20637. if (this._texturesEnabled === value) {
  20638. return;
  20639. }
  20640. this._texturesEnabled = value;
  20641. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20642. },
  20643. enumerable: true,
  20644. configurable: true
  20645. });
  20646. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20647. get: function () {
  20648. return this._skeletonsEnabled;
  20649. },
  20650. set: function (value) {
  20651. if (this._skeletonsEnabled === value) {
  20652. return;
  20653. }
  20654. this._skeletonsEnabled = value;
  20655. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20656. },
  20657. enumerable: true,
  20658. configurable: true
  20659. });
  20660. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  20661. get: function () {
  20662. if (!this._postProcessRenderPipelineManager) {
  20663. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20664. }
  20665. return this._postProcessRenderPipelineManager;
  20666. },
  20667. enumerable: true,
  20668. configurable: true
  20669. });
  20670. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  20671. get: function () {
  20672. if (!this._mainSoundTrack) {
  20673. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20674. }
  20675. return this._mainSoundTrack;
  20676. },
  20677. enumerable: true,
  20678. configurable: true
  20679. });
  20680. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  20681. get: function () {
  20682. return this._alternateRendering;
  20683. },
  20684. enumerable: true,
  20685. configurable: true
  20686. });
  20687. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20688. get: function () {
  20689. return this._frustumPlanes;
  20690. },
  20691. enumerable: true,
  20692. configurable: true
  20693. });
  20694. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  20695. /**
  20696. * Gets the current geometry buffer associated to the scene.
  20697. */
  20698. get: function () {
  20699. return this._geometryBufferRenderer;
  20700. },
  20701. /**
  20702. * Sets the current geometry buffer for the scene.
  20703. */
  20704. set: function (geometryBufferRenderer) {
  20705. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  20706. this._geometryBufferRenderer = geometryBufferRenderer;
  20707. }
  20708. },
  20709. enumerable: true,
  20710. configurable: true
  20711. });
  20712. Object.defineProperty(Scene.prototype, "debugLayer", {
  20713. // Properties
  20714. get: function () {
  20715. if (!this._debugLayer) {
  20716. this._debugLayer = new BABYLON.DebugLayer(this);
  20717. }
  20718. return this._debugLayer;
  20719. },
  20720. enumerable: true,
  20721. configurable: true
  20722. });
  20723. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20724. get: function () {
  20725. return this._workerCollisions;
  20726. },
  20727. set: function (enabled) {
  20728. if (!BABYLON.CollisionCoordinatorLegacy) {
  20729. return;
  20730. }
  20731. enabled = (enabled && !!Worker);
  20732. this._workerCollisions = enabled;
  20733. if (this.collisionCoordinator) {
  20734. this.collisionCoordinator.destroy();
  20735. }
  20736. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20737. this.collisionCoordinator.init(this);
  20738. },
  20739. enumerable: true,
  20740. configurable: true
  20741. });
  20742. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20743. get: function () {
  20744. return this._selectionOctree;
  20745. },
  20746. enumerable: true,
  20747. configurable: true
  20748. });
  20749. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20750. /**
  20751. * The mesh that is currently under the pointer.
  20752. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20753. */
  20754. get: function () {
  20755. return this._pointerOverMesh;
  20756. },
  20757. enumerable: true,
  20758. configurable: true
  20759. });
  20760. Object.defineProperty(Scene.prototype, "pointerX", {
  20761. /**
  20762. * Current on-screen X position of the pointer
  20763. * @return {number} X position of the pointer
  20764. */
  20765. get: function () {
  20766. return this._pointerX;
  20767. },
  20768. enumerable: true,
  20769. configurable: true
  20770. });
  20771. Object.defineProperty(Scene.prototype, "pointerY", {
  20772. /**
  20773. * Current on-screen Y position of the pointer
  20774. * @return {number} Y position of the pointer
  20775. */
  20776. get: function () {
  20777. return this._pointerY;
  20778. },
  20779. enumerable: true,
  20780. configurable: true
  20781. });
  20782. Scene.prototype.getCachedMaterial = function () {
  20783. return this._cachedMaterial;
  20784. };
  20785. Scene.prototype.getCachedEffect = function () {
  20786. return this._cachedEffect;
  20787. };
  20788. Scene.prototype.getCachedVisibility = function () {
  20789. return this._cachedVisibility;
  20790. };
  20791. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20792. if (visibility === void 0) { visibility = 1; }
  20793. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20794. };
  20795. Scene.prototype.getBoundingBoxRenderer = function () {
  20796. if (!this._boundingBoxRenderer) {
  20797. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20798. }
  20799. return this._boundingBoxRenderer;
  20800. };
  20801. Scene.prototype.getOutlineRenderer = function () {
  20802. return this._outlineRenderer;
  20803. };
  20804. Scene.prototype.getEngine = function () {
  20805. return this._engine;
  20806. };
  20807. Scene.prototype.getTotalVertices = function () {
  20808. return this._totalVertices.current;
  20809. };
  20810. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20811. get: function () {
  20812. return this._totalVertices;
  20813. },
  20814. enumerable: true,
  20815. configurable: true
  20816. });
  20817. Scene.prototype.getActiveIndices = function () {
  20818. return this._activeIndices.current;
  20819. };
  20820. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20821. get: function () {
  20822. return this._activeIndices;
  20823. },
  20824. enumerable: true,
  20825. configurable: true
  20826. });
  20827. Scene.prototype.getActiveParticles = function () {
  20828. return this._activeParticles.current;
  20829. };
  20830. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20831. get: function () {
  20832. return this._activeParticles;
  20833. },
  20834. enumerable: true,
  20835. configurable: true
  20836. });
  20837. Scene.prototype.getActiveBones = function () {
  20838. return this._activeBones.current;
  20839. };
  20840. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20841. get: function () {
  20842. return this._activeBones;
  20843. },
  20844. enumerable: true,
  20845. configurable: true
  20846. });
  20847. // Stats
  20848. Scene.prototype.getInterFramePerfCounter = function () {
  20849. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20850. return 0;
  20851. };
  20852. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20853. get: function () {
  20854. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20855. return null;
  20856. },
  20857. enumerable: true,
  20858. configurable: true
  20859. });
  20860. Scene.prototype.getLastFrameDuration = function () {
  20861. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20862. return 0;
  20863. };
  20864. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20865. get: function () {
  20866. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20867. return null;
  20868. },
  20869. enumerable: true,
  20870. configurable: true
  20871. });
  20872. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20873. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20874. return 0;
  20875. };
  20876. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20877. get: function () {
  20878. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20879. return null;
  20880. },
  20881. enumerable: true,
  20882. configurable: true
  20883. });
  20884. Scene.prototype.getActiveMeshes = function () {
  20885. return this._activeMeshes;
  20886. };
  20887. Scene.prototype.getRenderTargetsDuration = function () {
  20888. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20889. return 0;
  20890. };
  20891. Scene.prototype.getRenderDuration = function () {
  20892. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20893. return 0;
  20894. };
  20895. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20896. get: function () {
  20897. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20898. return null;
  20899. },
  20900. enumerable: true,
  20901. configurable: true
  20902. });
  20903. Scene.prototype.getParticlesDuration = function () {
  20904. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20905. return 0;
  20906. };
  20907. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20908. get: function () {
  20909. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20910. return null;
  20911. },
  20912. enumerable: true,
  20913. configurable: true
  20914. });
  20915. Scene.prototype.getSpritesDuration = function () {
  20916. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20917. return 0;
  20918. };
  20919. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20920. get: function () {
  20921. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20922. return null;
  20923. },
  20924. enumerable: true,
  20925. configurable: true
  20926. });
  20927. Scene.prototype.getAnimationRatio = function () {
  20928. return this._animationRatio;
  20929. };
  20930. Scene.prototype.getRenderId = function () {
  20931. return this._renderId;
  20932. };
  20933. Scene.prototype.incrementRenderId = function () {
  20934. this._renderId++;
  20935. };
  20936. Scene.prototype._updatePointerPosition = function (evt) {
  20937. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20938. if (!canvasRect) {
  20939. return;
  20940. }
  20941. this._pointerX = evt.clientX - canvasRect.left;
  20942. this._pointerY = evt.clientY - canvasRect.top;
  20943. this._unTranslatedPointerX = this._pointerX;
  20944. this._unTranslatedPointerY = this._pointerY;
  20945. };
  20946. Scene.prototype._createUbo = function () {
  20947. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20948. this._sceneUbo.addUniform("viewProjection", 16);
  20949. this._sceneUbo.addUniform("view", 16);
  20950. };
  20951. Scene.prototype._createAlternateUbo = function () {
  20952. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20953. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20954. this._alternateSceneUbo.addUniform("view", 16);
  20955. };
  20956. // Pointers handling
  20957. /**
  20958. * Use this method to simulate a pointer move on a mesh
  20959. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20960. */
  20961. Scene.prototype.simulatePointerMove = function (pickResult) {
  20962. var evt = new PointerEvent("pointermove");
  20963. return this._processPointerMove(pickResult, evt);
  20964. };
  20965. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20966. var canvas = this._engine.getRenderingCanvas();
  20967. if (!canvas) {
  20968. return this;
  20969. }
  20970. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20971. this.setPointerOverSprite(null);
  20972. this.setPointerOverMesh(pickResult.pickedMesh);
  20973. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20974. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20975. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20976. }
  20977. else {
  20978. canvas.style.cursor = this.hoverCursor;
  20979. }
  20980. }
  20981. else {
  20982. canvas.style.cursor = this.defaultCursor;
  20983. }
  20984. }
  20985. else {
  20986. this.setPointerOverMesh(null);
  20987. // Sprites
  20988. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20989. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20990. this.setPointerOverSprite(pickResult.pickedSprite);
  20991. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20992. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20993. }
  20994. else {
  20995. canvas.style.cursor = this.hoverCursor;
  20996. }
  20997. }
  20998. else {
  20999. this.setPointerOverSprite(null);
  21000. // Restore pointer
  21001. canvas.style.cursor = this.defaultCursor;
  21002. }
  21003. }
  21004. if (pickResult) {
  21005. if (this.onPointerMove) {
  21006. this.onPointerMove(evt, pickResult);
  21007. }
  21008. if (this.onPointerObservable.hasObservers()) {
  21009. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21010. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21011. this.onPointerObservable.notifyObservers(pi, type);
  21012. }
  21013. }
  21014. return this;
  21015. };
  21016. /**
  21017. * Use this method to simulate a pointer down on a mesh
  21018. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21019. */
  21020. Scene.prototype.simulatePointerDown = function (pickResult) {
  21021. var evt = new PointerEvent("pointerdown");
  21022. return this._processPointerDown(pickResult, evt);
  21023. };
  21024. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21025. var _this = this;
  21026. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21027. this._pickedDownMesh = pickResult.pickedMesh;
  21028. var actionManager = pickResult.pickedMesh.actionManager;
  21029. if (actionManager) {
  21030. if (actionManager.hasPickTriggers) {
  21031. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21032. switch (evt.button) {
  21033. case 0:
  21034. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21035. break;
  21036. case 1:
  21037. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21038. break;
  21039. case 2:
  21040. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21041. break;
  21042. }
  21043. }
  21044. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21045. window.setTimeout(function () {
  21046. 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);
  21047. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21048. if (_this._totalPointersPressed !== 0 &&
  21049. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21050. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21051. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21052. _this._startingPointerTime = 0;
  21053. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21054. }
  21055. }
  21056. }, Scene.LongPressDelay);
  21057. }
  21058. }
  21059. }
  21060. if (pickResult) {
  21061. if (this.onPointerDown) {
  21062. this.onPointerDown(evt, pickResult);
  21063. }
  21064. if (this.onPointerObservable.hasObservers()) {
  21065. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21066. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21067. this.onPointerObservable.notifyObservers(pi, type);
  21068. }
  21069. }
  21070. return this;
  21071. };
  21072. /**
  21073. * Use this method to simulate a pointer up on a mesh
  21074. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21075. */
  21076. Scene.prototype.simulatePointerUp = function (pickResult) {
  21077. var evt = new PointerEvent("pointerup");
  21078. var clickInfo = new ClickInfo();
  21079. clickInfo.singleClick = true;
  21080. clickInfo.ignore = true;
  21081. return this._processPointerUp(pickResult, evt, clickInfo);
  21082. };
  21083. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21084. if (pickResult && pickResult && pickResult.pickedMesh) {
  21085. this._pickedUpMesh = pickResult.pickedMesh;
  21086. if (this._pickedDownMesh === this._pickedUpMesh) {
  21087. if (this.onPointerPick) {
  21088. this.onPointerPick(evt, pickResult);
  21089. }
  21090. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21091. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21092. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21093. this.onPointerObservable.notifyObservers(pi, type);
  21094. }
  21095. }
  21096. if (pickResult.pickedMesh.actionManager) {
  21097. if (clickInfo.ignore) {
  21098. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21099. }
  21100. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21101. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21102. }
  21103. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21104. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21105. }
  21106. }
  21107. }
  21108. if (this._pickedDownMesh &&
  21109. this._pickedDownMesh.actionManager &&
  21110. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21111. this._pickedDownMesh !== this._pickedUpMesh) {
  21112. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21113. }
  21114. if (this.onPointerUp) {
  21115. this.onPointerUp(evt, pickResult);
  21116. }
  21117. if (this.onPointerObservable.hasObservers()) {
  21118. if (!clickInfo.ignore) {
  21119. if (!clickInfo.hasSwiped) {
  21120. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21121. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21122. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21123. this.onPointerObservable.notifyObservers(pi, type);
  21124. }
  21125. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21126. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21127. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21128. this.onPointerObservable.notifyObservers(pi, type);
  21129. }
  21130. }
  21131. }
  21132. else {
  21133. var type = BABYLON.PointerEventTypes.POINTERUP;
  21134. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21135. this.onPointerObservable.notifyObservers(pi, type);
  21136. }
  21137. }
  21138. return this;
  21139. };
  21140. /**
  21141. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21142. * @param attachUp defines if you want to attach events to pointerup
  21143. * @param attachDown defines if you want to attach events to pointerdown
  21144. * @param attachMove defines if you want to attach events to pointermove
  21145. */
  21146. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21147. var _this = this;
  21148. if (attachUp === void 0) { attachUp = true; }
  21149. if (attachDown === void 0) { attachDown = true; }
  21150. if (attachMove === void 0) { attachMove = true; }
  21151. this._initActionManager = function (act, clickInfo) {
  21152. if (!_this._meshPickProceed) {
  21153. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21154. _this._currentPickResult = pickResult;
  21155. if (pickResult) {
  21156. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21157. }
  21158. _this._meshPickProceed = true;
  21159. }
  21160. return act;
  21161. };
  21162. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21163. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21164. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21165. btn !== _this._previousButtonPressed) {
  21166. _this._doubleClickOccured = false;
  21167. clickInfo.singleClick = true;
  21168. clickInfo.ignore = false;
  21169. cb(clickInfo, _this._currentPickResult);
  21170. }
  21171. };
  21172. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21173. var clickInfo = new ClickInfo();
  21174. _this._currentPickResult = null;
  21175. var act = null;
  21176. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21177. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21178. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21179. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21180. act = _this._initActionManager(act, clickInfo);
  21181. if (act)
  21182. checkPicking = act.hasPickTriggers;
  21183. }
  21184. if (checkPicking) {
  21185. var btn = evt.button;
  21186. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21187. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21188. if (!clickInfo.hasSwiped) {
  21189. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21190. if (!checkSingleClickImmediately) {
  21191. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21192. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21193. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21194. act = _this._initActionManager(act, clickInfo);
  21195. if (act)
  21196. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21197. }
  21198. }
  21199. if (checkSingleClickImmediately) {
  21200. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21201. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21202. btn !== _this._previousButtonPressed) {
  21203. clickInfo.singleClick = true;
  21204. cb(clickInfo, _this._currentPickResult);
  21205. }
  21206. }
  21207. else {
  21208. // wait that no double click has been raised during the double click delay
  21209. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21210. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21211. }
  21212. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21213. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21214. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21215. act = _this._initActionManager(act, clickInfo);
  21216. if (act)
  21217. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21218. }
  21219. if (checkDoubleClick) {
  21220. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21221. if (btn === _this._previousButtonPressed &&
  21222. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21223. !_this._doubleClickOccured) {
  21224. // pointer has not moved for 2 clicks, it's a double click
  21225. if (!clickInfo.hasSwiped &&
  21226. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21227. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21228. _this._previousStartingPointerTime = 0;
  21229. _this._doubleClickOccured = true;
  21230. clickInfo.doubleClick = true;
  21231. clickInfo.ignore = false;
  21232. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21233. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21234. }
  21235. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21236. cb(clickInfo, _this._currentPickResult);
  21237. }
  21238. else {
  21239. _this._doubleClickOccured = false;
  21240. _this._previousStartingPointerTime = _this._startingPointerTime;
  21241. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21242. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21243. _this._previousButtonPressed = btn;
  21244. if (Scene.ExclusiveDoubleClickMode) {
  21245. if (_this._previousDelayedSimpleClickTimeout) {
  21246. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21247. }
  21248. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21249. cb(clickInfo, _this._previousPickResult);
  21250. }
  21251. else {
  21252. cb(clickInfo, _this._currentPickResult);
  21253. }
  21254. }
  21255. }
  21256. else {
  21257. _this._doubleClickOccured = false;
  21258. _this._previousStartingPointerTime = _this._startingPointerTime;
  21259. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21260. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21261. _this._previousButtonPressed = btn;
  21262. }
  21263. }
  21264. }
  21265. }
  21266. clickInfo.ignore = true;
  21267. cb(clickInfo, _this._currentPickResult);
  21268. };
  21269. this._spritePredicate = function (sprite) {
  21270. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21271. };
  21272. this._onPointerMove = function (evt) {
  21273. _this._updatePointerPosition(evt);
  21274. // PreObservable support
  21275. if (_this.onPrePointerObservable.hasObservers()) {
  21276. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21277. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21278. _this.onPrePointerObservable.notifyObservers(pi, type);
  21279. if (pi.skipOnPointerObservable) {
  21280. return;
  21281. }
  21282. }
  21283. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21284. return;
  21285. }
  21286. if (!_this.pointerMovePredicate) {
  21287. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21288. }
  21289. // Meshes
  21290. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21291. _this._processPointerMove(pickResult, evt);
  21292. };
  21293. this._onPointerDown = function (evt) {
  21294. _this._totalPointersPressed++;
  21295. _this._pickedDownMesh = null;
  21296. _this._meshPickProceed = false;
  21297. _this._updatePointerPosition(evt);
  21298. if (_this.preventDefaultOnPointerDown && canvas) {
  21299. evt.preventDefault();
  21300. canvas.focus();
  21301. }
  21302. // PreObservable support
  21303. if (_this.onPrePointerObservable.hasObservers()) {
  21304. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21305. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21306. _this.onPrePointerObservable.notifyObservers(pi, type);
  21307. if (pi.skipOnPointerObservable) {
  21308. return;
  21309. }
  21310. }
  21311. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21312. return;
  21313. }
  21314. _this._startingPointerPosition.x = _this._pointerX;
  21315. _this._startingPointerPosition.y = _this._pointerY;
  21316. _this._startingPointerTime = new Date().getTime();
  21317. if (!_this.pointerDownPredicate) {
  21318. _this.pointerDownPredicate = function (mesh) {
  21319. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21320. };
  21321. }
  21322. // Meshes
  21323. _this._pickedDownMesh = null;
  21324. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21325. _this._processPointerDown(pickResult, evt);
  21326. // Sprites
  21327. _this._pickedDownSprite = null;
  21328. if (_this.spriteManagers.length > 0) {
  21329. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21330. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21331. if (pickResult.pickedSprite.actionManager) {
  21332. _this._pickedDownSprite = pickResult.pickedSprite;
  21333. switch (evt.button) {
  21334. case 0:
  21335. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21336. break;
  21337. case 1:
  21338. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21339. break;
  21340. case 2:
  21341. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21342. break;
  21343. }
  21344. if (pickResult.pickedSprite.actionManager) {
  21345. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21346. }
  21347. }
  21348. }
  21349. }
  21350. };
  21351. this._onPointerUp = function (evt) {
  21352. if (_this._totalPointersPressed === 0) {
  21353. return; // So we need to test it the pointer down was pressed before.
  21354. }
  21355. _this._totalPointersPressed--;
  21356. _this._pickedUpMesh = null;
  21357. _this._meshPickProceed = false;
  21358. _this._updatePointerPosition(evt);
  21359. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  21360. // PreObservable support
  21361. if (_this.onPrePointerObservable.hasObservers()) {
  21362. if (!clickInfo.ignore) {
  21363. if (!clickInfo.hasSwiped) {
  21364. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21365. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21366. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21367. _this.onPrePointerObservable.notifyObservers(pi, type);
  21368. if (pi.skipOnPointerObservable) {
  21369. return;
  21370. }
  21371. }
  21372. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21373. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21374. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21375. _this.onPrePointerObservable.notifyObservers(pi, type);
  21376. if (pi.skipOnPointerObservable) {
  21377. return;
  21378. }
  21379. }
  21380. }
  21381. }
  21382. else {
  21383. var type = BABYLON.PointerEventTypes.POINTERUP;
  21384. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21385. _this.onPrePointerObservable.notifyObservers(pi, type);
  21386. if (pi.skipOnPointerObservable) {
  21387. return;
  21388. }
  21389. }
  21390. }
  21391. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21392. return;
  21393. }
  21394. if (!_this.pointerUpPredicate) {
  21395. _this.pointerUpPredicate = function (mesh) {
  21396. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21397. };
  21398. }
  21399. // Meshes
  21400. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  21401. _this._initActionManager(null, clickInfo);
  21402. }
  21403. if (!pickResult) {
  21404. pickResult = _this._currentPickResult;
  21405. }
  21406. _this._processPointerUp(pickResult, evt, clickInfo);
  21407. // Sprites
  21408. if (_this.spriteManagers.length > 0) {
  21409. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21410. if (spritePickResult) {
  21411. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  21412. if (spritePickResult.pickedSprite.actionManager) {
  21413. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21414. if (spritePickResult.pickedSprite.actionManager) {
  21415. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  21416. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21417. }
  21418. }
  21419. }
  21420. }
  21421. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  21422. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  21423. }
  21424. }
  21425. }
  21426. _this._previousPickResult = _this._currentPickResult;
  21427. });
  21428. };
  21429. this._onKeyDown = function (evt) {
  21430. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  21431. if (_this.onPreKeyboardObservable.hasObservers()) {
  21432. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21433. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21434. if (pi.skipOnPointerObservable) {
  21435. return;
  21436. }
  21437. }
  21438. if (_this.onKeyboardObservable.hasObservers()) {
  21439. var pi = new BABYLON.KeyboardInfo(type, evt);
  21440. _this.onKeyboardObservable.notifyObservers(pi, type);
  21441. }
  21442. if (_this.actionManager) {
  21443. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21444. }
  21445. };
  21446. this._onKeyUp = function (evt) {
  21447. var type = BABYLON.KeyboardEventTypes.KEYUP;
  21448. if (_this.onPreKeyboardObservable.hasObservers()) {
  21449. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21450. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21451. if (pi.skipOnPointerObservable) {
  21452. return;
  21453. }
  21454. }
  21455. if (_this.onKeyboardObservable.hasObservers()) {
  21456. var pi = new BABYLON.KeyboardInfo(type, evt);
  21457. _this.onKeyboardObservable.notifyObservers(pi, type);
  21458. }
  21459. if (_this.actionManager) {
  21460. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21461. }
  21462. };
  21463. var engine = this.getEngine();
  21464. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  21465. if (!canvas) {
  21466. return;
  21467. }
  21468. canvas.addEventListener("keydown", _this._onKeyDown, false);
  21469. canvas.addEventListener("keyup", _this._onKeyUp, false);
  21470. });
  21471. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  21472. if (!canvas) {
  21473. return;
  21474. }
  21475. canvas.removeEventListener("keydown", _this._onKeyDown);
  21476. canvas.removeEventListener("keyup", _this._onKeyUp);
  21477. });
  21478. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21479. var canvas = this._engine.getRenderingCanvas();
  21480. if (!canvas) {
  21481. return;
  21482. }
  21483. if (attachMove) {
  21484. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  21485. // Wheel
  21486. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  21487. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  21488. }
  21489. if (attachDown) {
  21490. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  21491. }
  21492. if (attachUp) {
  21493. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  21494. }
  21495. canvas.tabIndex = 1;
  21496. };
  21497. Scene.prototype.detachControl = function () {
  21498. var engine = this.getEngine();
  21499. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21500. var canvas = engine.getRenderingCanvas();
  21501. if (!canvas) {
  21502. return;
  21503. }
  21504. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  21505. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  21506. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  21507. if (this._onCanvasBlurObserver) {
  21508. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  21509. }
  21510. if (this._onCanvasFocusObserver) {
  21511. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  21512. }
  21513. // Wheel
  21514. canvas.removeEventListener('mousewheel', this._onPointerMove);
  21515. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  21516. // Keyboard
  21517. canvas.removeEventListener("keydown", this._onKeyDown);
  21518. canvas.removeEventListener("keyup", this._onKeyUp);
  21519. // Observables
  21520. this.onKeyboardObservable.clear();
  21521. this.onPreKeyboardObservable.clear();
  21522. this.onPointerObservable.clear();
  21523. this.onPrePointerObservable.clear();
  21524. };
  21525. /**
  21526. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  21527. * Delay loaded resources are not taking in account
  21528. * @return true if all required resources are ready
  21529. */
  21530. Scene.prototype.isReady = function () {
  21531. if (this._isDisposed) {
  21532. return false;
  21533. }
  21534. if (this._pendingData.length > 0) {
  21535. return false;
  21536. }
  21537. var index;
  21538. var engine = this.getEngine();
  21539. // Geometries
  21540. for (index = 0; index < this._geometries.length; index++) {
  21541. var geometry = this._geometries[index];
  21542. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21543. return false;
  21544. }
  21545. }
  21546. // Meshes
  21547. for (index = 0; index < this.meshes.length; index++) {
  21548. var mesh = this.meshes[index];
  21549. if (!mesh.isEnabled()) {
  21550. continue;
  21551. }
  21552. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21553. continue;
  21554. }
  21555. if (!mesh.isReady()) {
  21556. return false;
  21557. }
  21558. // Highlight layers
  21559. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  21560. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  21561. var layer = _a[_i];
  21562. if (!layer.hasMesh(mesh)) {
  21563. continue;
  21564. }
  21565. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  21566. var subMesh = _c[_b];
  21567. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  21568. return false;
  21569. }
  21570. }
  21571. }
  21572. }
  21573. return true;
  21574. };
  21575. Scene.prototype.resetCachedMaterial = function () {
  21576. this._cachedMaterial = null;
  21577. this._cachedEffect = null;
  21578. this._cachedVisibility = null;
  21579. };
  21580. Scene.prototype.registerBeforeRender = function (func) {
  21581. this.onBeforeRenderObservable.add(func);
  21582. };
  21583. Scene.prototype.unregisterBeforeRender = function (func) {
  21584. this.onBeforeRenderObservable.removeCallback(func);
  21585. };
  21586. Scene.prototype.registerAfterRender = function (func) {
  21587. this.onAfterRenderObservable.add(func);
  21588. };
  21589. Scene.prototype.unregisterAfterRender = function (func) {
  21590. this.onAfterRenderObservable.removeCallback(func);
  21591. };
  21592. Scene.prototype._executeOnceBeforeRender = function (func) {
  21593. var _this = this;
  21594. var execFunc = function () {
  21595. func();
  21596. setTimeout(function () {
  21597. _this.unregisterBeforeRender(execFunc);
  21598. });
  21599. };
  21600. this.registerBeforeRender(execFunc);
  21601. };
  21602. /**
  21603. * The provided function will run before render once and will be disposed afterwards.
  21604. * A timeout delay can be provided so that the function will be executed in N ms.
  21605. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  21606. * @param func The function to be executed.
  21607. * @param timeout optional delay in ms
  21608. */
  21609. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  21610. var _this = this;
  21611. if (timeout !== undefined) {
  21612. setTimeout(function () {
  21613. _this._executeOnceBeforeRender(func);
  21614. }, timeout);
  21615. }
  21616. else {
  21617. this._executeOnceBeforeRender(func);
  21618. }
  21619. };
  21620. Scene.prototype._addPendingData = function (data) {
  21621. this._pendingData.push(data);
  21622. };
  21623. Scene.prototype._removePendingData = function (data) {
  21624. var wasLoading = this.isLoading;
  21625. var index = this._pendingData.indexOf(data);
  21626. if (index !== -1) {
  21627. this._pendingData.splice(index, 1);
  21628. }
  21629. if (wasLoading && !this.isLoading) {
  21630. this.onDataLoadedObservable.notifyObservers(this);
  21631. }
  21632. };
  21633. Scene.prototype.getWaitingItemsCount = function () {
  21634. return this._pendingData.length;
  21635. };
  21636. Object.defineProperty(Scene.prototype, "isLoading", {
  21637. get: function () {
  21638. return this._pendingData.length > 0;
  21639. },
  21640. enumerable: true,
  21641. configurable: true
  21642. });
  21643. /**
  21644. * Registers a function to be executed when the scene is ready.
  21645. * @param {Function} func - the function to be executed.
  21646. */
  21647. Scene.prototype.executeWhenReady = function (func) {
  21648. var _this = this;
  21649. this.onReadyObservable.add(func);
  21650. if (this._executeWhenReadyTimeoutId !== -1) {
  21651. return;
  21652. }
  21653. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21654. _this._checkIsReady();
  21655. }, 150);
  21656. };
  21657. Scene.prototype._checkIsReady = function () {
  21658. var _this = this;
  21659. if (this.isReady()) {
  21660. this.onReadyObservable.notifyObservers(this);
  21661. this.onReadyObservable.clear();
  21662. this._executeWhenReadyTimeoutId = -1;
  21663. return;
  21664. }
  21665. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21666. _this._checkIsReady();
  21667. }, 150);
  21668. };
  21669. // Animations
  21670. /**
  21671. * Will start the animation sequence of a given target
  21672. * @param target - the target
  21673. * @param {number} from - from which frame should animation start
  21674. * @param {number} to - till which frame should animation run.
  21675. * @param {boolean} [loop] - should the animation loop
  21676. * @param {number} [speedRatio] - the speed in which to run the animation
  21677. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21678. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21679. * Returns {BABYLON.Animatable} the animatable object created for this animation
  21680. * See BABYLON.Animatable
  21681. */
  21682. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21683. if (speedRatio === void 0) { speedRatio = 1.0; }
  21684. if (from > to && speedRatio > 0) {
  21685. speedRatio *= -1;
  21686. }
  21687. this.stopAnimation(target);
  21688. if (!animatable) {
  21689. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21690. }
  21691. // Local animations
  21692. if (target.animations) {
  21693. animatable.appendAnimations(target, target.animations);
  21694. }
  21695. // Children animations
  21696. if (target.getAnimatables) {
  21697. var animatables = target.getAnimatables();
  21698. for (var index = 0; index < animatables.length; index++) {
  21699. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21700. }
  21701. }
  21702. animatable.reset();
  21703. return animatable;
  21704. };
  21705. /**
  21706. * Begin a new animation on a given node
  21707. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21708. * @param {BABYLON.Animation[]} defines the list of animations to start
  21709. * @param {number} from defines the initial value
  21710. * @param {number} to defines the final value
  21711. * @param {boolean} loop defines if you want animation to loop (off by default)
  21712. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21713. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21714. * @returns the list of created animatables
  21715. */
  21716. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21717. if (speedRatio === undefined) {
  21718. speedRatio = 1.0;
  21719. }
  21720. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21721. return animatable;
  21722. };
  21723. /**
  21724. * Begin a new animation on a given node and its hierarchy
  21725. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21726. * @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.
  21727. * @param {BABYLON.Animation[]} defines the list of animations to start
  21728. * @param {number} from defines the initial value
  21729. * @param {number} to defines the final value
  21730. * @param {boolean} loop defines if you want animation to loop (off by default)
  21731. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21732. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21733. * @returns the list of animatables created for all nodes
  21734. */
  21735. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21736. var children = target.getDescendants(directDescendantsOnly);
  21737. var result = [];
  21738. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21739. var child = children_1[_i];
  21740. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21741. }
  21742. return result;
  21743. };
  21744. Scene.prototype.getAnimatableByTarget = function (target) {
  21745. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21746. if (this._activeAnimatables[index].target === target) {
  21747. return this._activeAnimatables[index];
  21748. }
  21749. }
  21750. return null;
  21751. };
  21752. Object.defineProperty(Scene.prototype, "animatables", {
  21753. get: function () {
  21754. return this._activeAnimatables;
  21755. },
  21756. enumerable: true,
  21757. configurable: true
  21758. });
  21759. /**
  21760. * Will stop the animation of the given target
  21761. * @param target - the target
  21762. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21763. * @see beginAnimation
  21764. */
  21765. Scene.prototype.stopAnimation = function (target, animationName) {
  21766. var animatable = this.getAnimatableByTarget(target);
  21767. if (animatable) {
  21768. animatable.stop(animationName);
  21769. }
  21770. };
  21771. /**
  21772. * Stops and removes all animations that have been applied to the scene
  21773. */
  21774. Scene.prototype.stopAllAnimations = function () {
  21775. if (this._activeAnimatables) {
  21776. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21777. this._activeAnimatables[i].stop();
  21778. }
  21779. this._activeAnimatables = [];
  21780. }
  21781. };
  21782. Scene.prototype._animate = function () {
  21783. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21784. return;
  21785. }
  21786. // Getting time
  21787. var now = BABYLON.Tools.Now;
  21788. if (!this._animationTimeLast) {
  21789. if (this._pendingData.length > 0) {
  21790. return;
  21791. }
  21792. this._animationTimeLast = now;
  21793. }
  21794. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21795. this._animationTime += deltaTime;
  21796. this._animationTimeLast = now;
  21797. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21798. this._activeAnimatables[index]._animate(this._animationTime);
  21799. }
  21800. };
  21801. // Matrix
  21802. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21803. this._useAlternateCameraConfiguration = active;
  21804. };
  21805. Scene.prototype.getViewMatrix = function () {
  21806. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21807. };
  21808. Scene.prototype.getProjectionMatrix = function () {
  21809. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21810. };
  21811. Scene.prototype.getTransformMatrix = function () {
  21812. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21813. };
  21814. Scene.prototype.setTransformMatrix = function (view, projection) {
  21815. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21816. return;
  21817. }
  21818. this._viewUpdateFlag = view.updateFlag;
  21819. this._projectionUpdateFlag = projection.updateFlag;
  21820. this._viewMatrix = view;
  21821. this._projectionMatrix = projection;
  21822. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21823. // Update frustum
  21824. if (!this._frustumPlanes) {
  21825. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21826. }
  21827. else {
  21828. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21829. }
  21830. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21831. var otherCamera = this.activeCamera._alternateCamera;
  21832. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21833. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21834. }
  21835. if (this._sceneUbo.useUbo) {
  21836. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21837. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21838. this._sceneUbo.update();
  21839. }
  21840. };
  21841. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21842. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21843. return;
  21844. }
  21845. this._alternateViewUpdateFlag = view.updateFlag;
  21846. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21847. this._alternateViewMatrix = view;
  21848. this._alternateProjectionMatrix = projection;
  21849. if (!this._alternateTransformMatrix) {
  21850. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21851. }
  21852. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21853. if (!this._alternateSceneUbo) {
  21854. this._createAlternateUbo();
  21855. }
  21856. if (this._alternateSceneUbo.useUbo) {
  21857. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21858. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21859. this._alternateSceneUbo.update();
  21860. }
  21861. };
  21862. Scene.prototype.getSceneUniformBuffer = function () {
  21863. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21864. };
  21865. // Methods
  21866. Scene.prototype.getUniqueId = function () {
  21867. var result = Scene._uniqueIdCounter;
  21868. Scene._uniqueIdCounter++;
  21869. return result;
  21870. };
  21871. Scene.prototype.addMesh = function (newMesh) {
  21872. this.meshes.push(newMesh);
  21873. //notify the collision coordinator
  21874. if (this.collisionCoordinator) {
  21875. this.collisionCoordinator.onMeshAdded(newMesh);
  21876. }
  21877. newMesh._resyncLightSources();
  21878. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21879. };
  21880. Scene.prototype.removeMesh = function (toRemove) {
  21881. var index = this.meshes.indexOf(toRemove);
  21882. if (index !== -1) {
  21883. // Remove from the scene if mesh found
  21884. this.meshes.splice(index, 1);
  21885. }
  21886. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21887. return index;
  21888. };
  21889. Scene.prototype.addTransformNode = function (newTransformNode) {
  21890. this.transformNodes.push(newTransformNode);
  21891. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21892. };
  21893. Scene.prototype.removeTransformNode = function (toRemove) {
  21894. var index = this.transformNodes.indexOf(toRemove);
  21895. if (index !== -1) {
  21896. // Remove from the scene if found
  21897. this.transformNodes.splice(index, 1);
  21898. }
  21899. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21900. return index;
  21901. };
  21902. Scene.prototype.removeSkeleton = function (toRemove) {
  21903. var index = this.skeletons.indexOf(toRemove);
  21904. if (index !== -1) {
  21905. // Remove from the scene if found
  21906. this.skeletons.splice(index, 1);
  21907. }
  21908. return index;
  21909. };
  21910. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21911. var index = this.morphTargetManagers.indexOf(toRemove);
  21912. if (index !== -1) {
  21913. // Remove from the scene if found
  21914. this.morphTargetManagers.splice(index, 1);
  21915. }
  21916. return index;
  21917. };
  21918. Scene.prototype.removeLight = function (toRemove) {
  21919. var index = this.lights.indexOf(toRemove);
  21920. if (index !== -1) {
  21921. // Remove from meshes
  21922. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21923. var mesh = _a[_i];
  21924. mesh._removeLightSource(toRemove);
  21925. }
  21926. // Remove from the scene if mesh found
  21927. this.lights.splice(index, 1);
  21928. this.sortLightsByPriority();
  21929. }
  21930. this.onLightRemovedObservable.notifyObservers(toRemove);
  21931. return index;
  21932. };
  21933. Scene.prototype.removeCamera = function (toRemove) {
  21934. var index = this.cameras.indexOf(toRemove);
  21935. if (index !== -1) {
  21936. // Remove from the scene if mesh found
  21937. this.cameras.splice(index, 1);
  21938. }
  21939. // Remove from activeCameras
  21940. var index2 = this.activeCameras.indexOf(toRemove);
  21941. if (index2 !== -1) {
  21942. // Remove from the scene if mesh found
  21943. this.activeCameras.splice(index2, 1);
  21944. }
  21945. // Reset the activeCamera
  21946. if (this.activeCamera === toRemove) {
  21947. if (this.cameras.length > 0) {
  21948. this.activeCamera = this.cameras[0];
  21949. }
  21950. else {
  21951. this.activeCamera = null;
  21952. }
  21953. }
  21954. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21955. return index;
  21956. };
  21957. Scene.prototype.removeParticleSystem = function (toRemove) {
  21958. var index = this.particleSystems.indexOf(toRemove);
  21959. if (index !== -1) {
  21960. this.particleSystems.splice(index, 1);
  21961. }
  21962. return index;
  21963. };
  21964. ;
  21965. Scene.prototype.removeAnimation = function (toRemove) {
  21966. var index = this.animations.indexOf(toRemove);
  21967. if (index !== -1) {
  21968. this.animations.splice(index, 1);
  21969. }
  21970. return index;
  21971. };
  21972. ;
  21973. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21974. var index = this.multiMaterials.indexOf(toRemove);
  21975. if (index !== -1) {
  21976. this.multiMaterials.splice(index, 1);
  21977. }
  21978. return index;
  21979. };
  21980. ;
  21981. Scene.prototype.removeMaterial = function (toRemove) {
  21982. var index = this.materials.indexOf(toRemove);
  21983. if (index !== -1) {
  21984. this.materials.splice(index, 1);
  21985. }
  21986. return index;
  21987. };
  21988. ;
  21989. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21990. var index = this.lensFlareSystems.indexOf(toRemove);
  21991. if (index !== -1) {
  21992. this.lensFlareSystems.splice(index, 1);
  21993. }
  21994. return index;
  21995. };
  21996. ;
  21997. Scene.prototype.removeActionManager = function (toRemove) {
  21998. var index = this._actionManagers.indexOf(toRemove);
  21999. if (index !== -1) {
  22000. this._actionManagers.splice(index, 1);
  22001. }
  22002. return index;
  22003. };
  22004. ;
  22005. Scene.prototype.addLight = function (newLight) {
  22006. this.lights.push(newLight);
  22007. this.sortLightsByPriority();
  22008. // Add light to all meshes (To support if the light is removed and then readded)
  22009. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22010. var mesh = _a[_i];
  22011. if (mesh._lightSources.indexOf(newLight) === -1) {
  22012. mesh._lightSources.push(newLight);
  22013. mesh._resyncLightSources();
  22014. }
  22015. }
  22016. this.onNewLightAddedObservable.notifyObservers(newLight);
  22017. };
  22018. Scene.prototype.sortLightsByPriority = function () {
  22019. if (this.requireLightSorting) {
  22020. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22021. }
  22022. };
  22023. Scene.prototype.addCamera = function (newCamera) {
  22024. this.cameras.push(newCamera);
  22025. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22026. };
  22027. Scene.prototype.addSkeleton = function (newSkeleton) {
  22028. this.skeletons.push(newSkeleton);
  22029. };
  22030. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22031. this.particleSystems.push(newParticleSystem);
  22032. };
  22033. Scene.prototype.addAnimation = function (newAnimation) {
  22034. this.animations.push(newAnimation);
  22035. };
  22036. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22037. this.multiMaterials.push(newMultiMaterial);
  22038. };
  22039. Scene.prototype.addMaterial = function (newMaterial) {
  22040. this.materials.push(newMaterial);
  22041. };
  22042. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22043. this.morphTargetManagers.push(newMorphTargetManager);
  22044. };
  22045. Scene.prototype.addGeometry = function (newGeometrie) {
  22046. this._geometries.push(newGeometrie);
  22047. };
  22048. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22049. this.lensFlareSystems.push(newLensFlareSystem);
  22050. };
  22051. Scene.prototype.addActionManager = function (newActionManager) {
  22052. this._actionManagers.push(newActionManager);
  22053. };
  22054. /**
  22055. * Switch active camera
  22056. * @param {Camera} newCamera - new active camera
  22057. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22058. */
  22059. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22060. if (attachControl === void 0) { attachControl = true; }
  22061. var canvas = this._engine.getRenderingCanvas();
  22062. if (!canvas) {
  22063. return;
  22064. }
  22065. if (this.activeCamera) {
  22066. this.activeCamera.detachControl(canvas);
  22067. }
  22068. this.activeCamera = newCamera;
  22069. if (attachControl) {
  22070. newCamera.attachControl(canvas);
  22071. }
  22072. };
  22073. /**
  22074. * sets the active camera of the scene using its ID
  22075. * @param {string} id - the camera's ID
  22076. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22077. * @see activeCamera
  22078. */
  22079. Scene.prototype.setActiveCameraByID = function (id) {
  22080. var camera = this.getCameraByID(id);
  22081. if (camera) {
  22082. this.activeCamera = camera;
  22083. return camera;
  22084. }
  22085. return null;
  22086. };
  22087. /**
  22088. * sets the active camera of the scene using its name
  22089. * @param {string} name - the camera's name
  22090. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22091. * @see activeCamera
  22092. */
  22093. Scene.prototype.setActiveCameraByName = function (name) {
  22094. var camera = this.getCameraByName(name);
  22095. if (camera) {
  22096. this.activeCamera = camera;
  22097. return camera;
  22098. }
  22099. return null;
  22100. };
  22101. /**
  22102. * get an animation group using its name
  22103. * @param {string} the material's name
  22104. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22105. */
  22106. Scene.prototype.getAnimationGroupByName = function (name) {
  22107. for (var index = 0; index < this.animationGroups.length; index++) {
  22108. if (this.animationGroups[index].name === name) {
  22109. return this.animationGroups[index];
  22110. }
  22111. }
  22112. return null;
  22113. };
  22114. /**
  22115. * get a material using its id
  22116. * @param {string} the material's ID
  22117. * @return {BABYLON.Material|null} the material or null if none found.
  22118. */
  22119. Scene.prototype.getMaterialByID = function (id) {
  22120. for (var index = 0; index < this.materials.length; index++) {
  22121. if (this.materials[index].id === id) {
  22122. return this.materials[index];
  22123. }
  22124. }
  22125. return null;
  22126. };
  22127. /**
  22128. * get a material using its name
  22129. * @param {string} the material's name
  22130. * @return {BABYLON.Material|null} the material or null if none found.
  22131. */
  22132. Scene.prototype.getMaterialByName = function (name) {
  22133. for (var index = 0; index < this.materials.length; index++) {
  22134. if (this.materials[index].name === name) {
  22135. return this.materials[index];
  22136. }
  22137. }
  22138. return null;
  22139. };
  22140. Scene.prototype.getLensFlareSystemByName = function (name) {
  22141. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22142. if (this.lensFlareSystems[index].name === name) {
  22143. return this.lensFlareSystems[index];
  22144. }
  22145. }
  22146. return null;
  22147. };
  22148. Scene.prototype.getLensFlareSystemByID = function (id) {
  22149. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22150. if (this.lensFlareSystems[index].id === id) {
  22151. return this.lensFlareSystems[index];
  22152. }
  22153. }
  22154. return null;
  22155. };
  22156. Scene.prototype.getCameraByID = function (id) {
  22157. for (var index = 0; index < this.cameras.length; index++) {
  22158. if (this.cameras[index].id === id) {
  22159. return this.cameras[index];
  22160. }
  22161. }
  22162. return null;
  22163. };
  22164. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22165. for (var index = 0; index < this.cameras.length; index++) {
  22166. if (this.cameras[index].uniqueId === uniqueId) {
  22167. return this.cameras[index];
  22168. }
  22169. }
  22170. return null;
  22171. };
  22172. /**
  22173. * get a camera using its name
  22174. * @param {string} the camera's name
  22175. * @return {BABYLON.Camera|null} the camera or null if none found.
  22176. */
  22177. Scene.prototype.getCameraByName = function (name) {
  22178. for (var index = 0; index < this.cameras.length; index++) {
  22179. if (this.cameras[index].name === name) {
  22180. return this.cameras[index];
  22181. }
  22182. }
  22183. return null;
  22184. };
  22185. /**
  22186. * get a bone using its id
  22187. * @param {string} the bone's id
  22188. * @return {BABYLON.Bone|null} the bone or null if not found
  22189. */
  22190. Scene.prototype.getBoneByID = function (id) {
  22191. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22192. var skeleton = this.skeletons[skeletonIndex];
  22193. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22194. if (skeleton.bones[boneIndex].id === id) {
  22195. return skeleton.bones[boneIndex];
  22196. }
  22197. }
  22198. }
  22199. return null;
  22200. };
  22201. /**
  22202. * get a bone using its id
  22203. * @param {string} the bone's name
  22204. * @return {BABYLON.Bone|null} the bone or null if not found
  22205. */
  22206. Scene.prototype.getBoneByName = function (name) {
  22207. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22208. var skeleton = this.skeletons[skeletonIndex];
  22209. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22210. if (skeleton.bones[boneIndex].name === name) {
  22211. return skeleton.bones[boneIndex];
  22212. }
  22213. }
  22214. }
  22215. return null;
  22216. };
  22217. /**
  22218. * get a light node using its name
  22219. * @param {string} the light's name
  22220. * @return {BABYLON.Light|null} the light or null if none found.
  22221. */
  22222. Scene.prototype.getLightByName = function (name) {
  22223. for (var index = 0; index < this.lights.length; index++) {
  22224. if (this.lights[index].name === name) {
  22225. return this.lights[index];
  22226. }
  22227. }
  22228. return null;
  22229. };
  22230. /**
  22231. * get a light node using its ID
  22232. * @param {string} the light's id
  22233. * @return {BABYLON.Light|null} the light or null if none found.
  22234. */
  22235. Scene.prototype.getLightByID = function (id) {
  22236. for (var index = 0; index < this.lights.length; index++) {
  22237. if (this.lights[index].id === id) {
  22238. return this.lights[index];
  22239. }
  22240. }
  22241. return null;
  22242. };
  22243. /**
  22244. * get a light node using its scene-generated unique ID
  22245. * @param {number} the light's unique id
  22246. * @return {BABYLON.Light|null} the light or null if none found.
  22247. */
  22248. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22249. for (var index = 0; index < this.lights.length; index++) {
  22250. if (this.lights[index].uniqueId === uniqueId) {
  22251. return this.lights[index];
  22252. }
  22253. }
  22254. return null;
  22255. };
  22256. /**
  22257. * get a particle system by id
  22258. * @param id {number} the particle system id
  22259. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22260. */
  22261. Scene.prototype.getParticleSystemByID = function (id) {
  22262. for (var index = 0; index < this.particleSystems.length; index++) {
  22263. if (this.particleSystems[index].id === id) {
  22264. return this.particleSystems[index];
  22265. }
  22266. }
  22267. return null;
  22268. };
  22269. /**
  22270. * get a geometry using its ID
  22271. * @param {string} the geometry's id
  22272. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22273. */
  22274. Scene.prototype.getGeometryByID = function (id) {
  22275. for (var index = 0; index < this._geometries.length; index++) {
  22276. if (this._geometries[index].id === id) {
  22277. return this._geometries[index];
  22278. }
  22279. }
  22280. return null;
  22281. };
  22282. /**
  22283. * add a new geometry to this scene.
  22284. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22285. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22286. * @return {boolean} was the geometry added or not
  22287. */
  22288. Scene.prototype.pushGeometry = function (geometry, force) {
  22289. if (!force && this.getGeometryByID(geometry.id)) {
  22290. return false;
  22291. }
  22292. this._geometries.push(geometry);
  22293. //notify the collision coordinator
  22294. if (this.collisionCoordinator) {
  22295. this.collisionCoordinator.onGeometryAdded(geometry);
  22296. }
  22297. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22298. return true;
  22299. };
  22300. /**
  22301. * Removes an existing geometry
  22302. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22303. * @return {boolean} was the geometry removed or not
  22304. */
  22305. Scene.prototype.removeGeometry = function (geometry) {
  22306. var index = this._geometries.indexOf(geometry);
  22307. if (index > -1) {
  22308. this._geometries.splice(index, 1);
  22309. //notify the collision coordinator
  22310. if (this.collisionCoordinator) {
  22311. this.collisionCoordinator.onGeometryDeleted(geometry);
  22312. }
  22313. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22314. return true;
  22315. }
  22316. return false;
  22317. };
  22318. Scene.prototype.getGeometries = function () {
  22319. return this._geometries;
  22320. };
  22321. /**
  22322. * Get the first added mesh found of a given ID
  22323. * @param {string} id - the id to search for
  22324. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22325. */
  22326. Scene.prototype.getMeshByID = function (id) {
  22327. for (var index = 0; index < this.meshes.length; index++) {
  22328. if (this.meshes[index].id === id) {
  22329. return this.meshes[index];
  22330. }
  22331. }
  22332. return null;
  22333. };
  22334. Scene.prototype.getMeshesByID = function (id) {
  22335. return this.meshes.filter(function (m) {
  22336. return m.id === id;
  22337. });
  22338. };
  22339. /**
  22340. * Get the first added transform node found of a given ID
  22341. * @param {string} id - the id to search for
  22342. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  22343. */
  22344. Scene.prototype.getTransformNodeByID = function (id) {
  22345. for (var index = 0; index < this.transformNodes.length; index++) {
  22346. if (this.transformNodes[index].id === id) {
  22347. return this.transformNodes[index];
  22348. }
  22349. }
  22350. return null;
  22351. };
  22352. Scene.prototype.getTransformNodesByID = function (id) {
  22353. return this.transformNodes.filter(function (m) {
  22354. return m.id === id;
  22355. });
  22356. };
  22357. /**
  22358. * Get a mesh with its auto-generated unique id
  22359. * @param {number} uniqueId - the unique id to search for
  22360. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22361. */
  22362. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  22363. for (var index = 0; index < this.meshes.length; index++) {
  22364. if (this.meshes[index].uniqueId === uniqueId) {
  22365. return this.meshes[index];
  22366. }
  22367. }
  22368. return null;
  22369. };
  22370. /**
  22371. * Get a the last added mesh found of a given ID
  22372. * @param {string} id - the id to search for
  22373. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22374. */
  22375. Scene.prototype.getLastMeshByID = function (id) {
  22376. for (var index = this.meshes.length - 1; index >= 0; index--) {
  22377. if (this.meshes[index].id === id) {
  22378. return this.meshes[index];
  22379. }
  22380. }
  22381. return null;
  22382. };
  22383. /**
  22384. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  22385. * @param {string} id - the id to search for
  22386. * @return {BABYLON.Node|null} the node found or null if not found at all.
  22387. */
  22388. Scene.prototype.getLastEntryByID = function (id) {
  22389. var index;
  22390. for (index = this.meshes.length - 1; index >= 0; index--) {
  22391. if (this.meshes[index].id === id) {
  22392. return this.meshes[index];
  22393. }
  22394. }
  22395. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  22396. if (this.transformNodes[index].id === id) {
  22397. return this.transformNodes[index];
  22398. }
  22399. }
  22400. for (index = this.cameras.length - 1; index >= 0; index--) {
  22401. if (this.cameras[index].id === id) {
  22402. return this.cameras[index];
  22403. }
  22404. }
  22405. for (index = this.lights.length - 1; index >= 0; index--) {
  22406. if (this.lights[index].id === id) {
  22407. return this.lights[index];
  22408. }
  22409. }
  22410. return null;
  22411. };
  22412. Scene.prototype.getNodeByID = function (id) {
  22413. var mesh = this.getMeshByID(id);
  22414. if (mesh) {
  22415. return mesh;
  22416. }
  22417. var light = this.getLightByID(id);
  22418. if (light) {
  22419. return light;
  22420. }
  22421. var camera = this.getCameraByID(id);
  22422. if (camera) {
  22423. return camera;
  22424. }
  22425. var bone = this.getBoneByID(id);
  22426. return bone;
  22427. };
  22428. Scene.prototype.getNodeByName = function (name) {
  22429. var mesh = this.getMeshByName(name);
  22430. if (mesh) {
  22431. return mesh;
  22432. }
  22433. var light = this.getLightByName(name);
  22434. if (light) {
  22435. return light;
  22436. }
  22437. var camera = this.getCameraByName(name);
  22438. if (camera) {
  22439. return camera;
  22440. }
  22441. var bone = this.getBoneByName(name);
  22442. return bone;
  22443. };
  22444. Scene.prototype.getMeshByName = function (name) {
  22445. for (var index = 0; index < this.meshes.length; index++) {
  22446. if (this.meshes[index].name === name) {
  22447. return this.meshes[index];
  22448. }
  22449. }
  22450. return null;
  22451. };
  22452. Scene.prototype.getTransformNodeByName = function (name) {
  22453. for (var index = 0; index < this.transformNodes.length; index++) {
  22454. if (this.transformNodes[index].name === name) {
  22455. return this.transformNodes[index];
  22456. }
  22457. }
  22458. return null;
  22459. };
  22460. Scene.prototype.getSoundByName = function (name) {
  22461. var index;
  22462. if (BABYLON.AudioEngine) {
  22463. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  22464. if (this.mainSoundTrack.soundCollection[index].name === name) {
  22465. return this.mainSoundTrack.soundCollection[index];
  22466. }
  22467. }
  22468. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  22469. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  22470. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  22471. return this.soundTracks[sdIndex].soundCollection[index];
  22472. }
  22473. }
  22474. }
  22475. }
  22476. return null;
  22477. };
  22478. Scene.prototype.getLastSkeletonByID = function (id) {
  22479. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  22480. if (this.skeletons[index].id === id) {
  22481. return this.skeletons[index];
  22482. }
  22483. }
  22484. return null;
  22485. };
  22486. Scene.prototype.getSkeletonById = function (id) {
  22487. for (var index = 0; index < this.skeletons.length; index++) {
  22488. if (this.skeletons[index].id === id) {
  22489. return this.skeletons[index];
  22490. }
  22491. }
  22492. return null;
  22493. };
  22494. Scene.prototype.getSkeletonByName = function (name) {
  22495. for (var index = 0; index < this.skeletons.length; index++) {
  22496. if (this.skeletons[index].name === name) {
  22497. return this.skeletons[index];
  22498. }
  22499. }
  22500. return null;
  22501. };
  22502. Scene.prototype.getMorphTargetManagerById = function (id) {
  22503. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  22504. if (this.morphTargetManagers[index].uniqueId === id) {
  22505. return this.morphTargetManagers[index];
  22506. }
  22507. }
  22508. return null;
  22509. };
  22510. Scene.prototype.isActiveMesh = function (mesh) {
  22511. return (this._activeMeshes.indexOf(mesh) !== -1);
  22512. };
  22513. /**
  22514. * Return a the first highlight layer of the scene with a given name.
  22515. * @param name The name of the highlight layer to look for.
  22516. * @return The highlight layer if found otherwise null.
  22517. */
  22518. Scene.prototype.getHighlightLayerByName = function (name) {
  22519. for (var index = 0; index < this.highlightLayers.length; index++) {
  22520. if (this.highlightLayers[index].name === name) {
  22521. return this.highlightLayers[index];
  22522. }
  22523. }
  22524. return null;
  22525. };
  22526. Object.defineProperty(Scene.prototype, "uid", {
  22527. /**
  22528. * Return a unique id as a string which can serve as an identifier for the scene
  22529. */
  22530. get: function () {
  22531. if (!this._uid) {
  22532. this._uid = BABYLON.Tools.RandomId();
  22533. }
  22534. return this._uid;
  22535. },
  22536. enumerable: true,
  22537. configurable: true
  22538. });
  22539. /**
  22540. * Add an externaly attached data from its key.
  22541. * This method call will fail and return false, if such key already exists.
  22542. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  22543. * @param key the unique key that identifies the data
  22544. * @param data the data object to associate to the key for this Engine instance
  22545. * @return true if no such key were already present and the data was added successfully, false otherwise
  22546. */
  22547. Scene.prototype.addExternalData = function (key, data) {
  22548. if (!this._externalData) {
  22549. this._externalData = new BABYLON.StringDictionary();
  22550. }
  22551. return this._externalData.add(key, data);
  22552. };
  22553. /**
  22554. * Get an externaly attached data from its key
  22555. * @param key the unique key that identifies the data
  22556. * @return the associated data, if present (can be null), or undefined if not present
  22557. */
  22558. Scene.prototype.getExternalData = function (key) {
  22559. if (!this._externalData) {
  22560. return null;
  22561. }
  22562. return this._externalData.get(key);
  22563. };
  22564. /**
  22565. * Get an externaly attached data from its key, create it using a factory if it's not already present
  22566. * @param key the unique key that identifies the data
  22567. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  22568. * @return the associated data, can be null if the factory returned null.
  22569. */
  22570. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  22571. if (!this._externalData) {
  22572. this._externalData = new BABYLON.StringDictionary();
  22573. }
  22574. return this._externalData.getOrAddWithFactory(key, factory);
  22575. };
  22576. /**
  22577. * Remove an externaly attached data from the Engine instance
  22578. * @param key the unique key that identifies the data
  22579. * @return true if the data was successfully removed, false if it doesn't exist
  22580. */
  22581. Scene.prototype.removeExternalData = function (key) {
  22582. return this._externalData.remove(key);
  22583. };
  22584. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  22585. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  22586. if (mesh.showSubMeshesBoundingBox) {
  22587. var boundingInfo = subMesh.getBoundingInfo();
  22588. if (boundingInfo !== null && boundingInfo !== undefined) {
  22589. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22590. }
  22591. }
  22592. var material = subMesh.getMaterial();
  22593. if (material !== null && material !== undefined) {
  22594. // Render targets
  22595. if (material.getRenderTargetTextures !== undefined) {
  22596. if (this._processedMaterials.indexOf(material) === -1) {
  22597. this._processedMaterials.push(material);
  22598. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22599. }
  22600. }
  22601. // Dispatch
  22602. this._activeIndices.addCount(subMesh.indexCount, false);
  22603. this._renderingManager.dispatch(subMesh, mesh, material);
  22604. }
  22605. }
  22606. };
  22607. Scene.prototype._isInIntermediateRendering = function () {
  22608. return this._intermediateRendering;
  22609. };
  22610. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  22611. this._activeMeshCandidateProvider = provider;
  22612. };
  22613. Scene.prototype.getActiveMeshCandidateProvider = function () {
  22614. return this._activeMeshCandidateProvider;
  22615. };
  22616. /**
  22617. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  22618. */
  22619. Scene.prototype.freezeActiveMeshes = function () {
  22620. this._evaluateActiveMeshes();
  22621. this._activeMeshesFrozen = true;
  22622. return this;
  22623. };
  22624. /**
  22625. * Use this function to restart evaluating active meshes on every frame
  22626. */
  22627. Scene.prototype.unfreezeActiveMeshes = function () {
  22628. this._activeMeshesFrozen = false;
  22629. return this;
  22630. };
  22631. Scene.prototype._evaluateActiveMeshes = function () {
  22632. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  22633. return;
  22634. }
  22635. if (!this.activeCamera) {
  22636. return;
  22637. }
  22638. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  22639. this.activeCamera._activeMeshes.reset();
  22640. this._activeMeshes.reset();
  22641. this._renderingManager.reset();
  22642. this._processedMaterials.reset();
  22643. this._activeParticleSystems.reset();
  22644. this._activeSkeletons.reset();
  22645. this._softwareSkinnedMeshes.reset();
  22646. if (this._boundingBoxRenderer) {
  22647. this._boundingBoxRenderer.reset();
  22648. }
  22649. // Meshes
  22650. var meshes;
  22651. var len;
  22652. var checkIsEnabled = true;
  22653. // Determine mesh candidates
  22654. if (this._activeMeshCandidateProvider !== undefined) {
  22655. // Use _activeMeshCandidateProvider
  22656. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  22657. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  22658. if (meshes !== undefined) {
  22659. len = meshes.length;
  22660. }
  22661. else {
  22662. len = 0;
  22663. }
  22664. }
  22665. else if (this._selectionOctree !== undefined) {
  22666. // Octree
  22667. var selection = this._selectionOctree.select(this._frustumPlanes);
  22668. meshes = selection.data;
  22669. len = selection.length;
  22670. }
  22671. else {
  22672. // Full scene traversal
  22673. len = this.meshes.length;
  22674. meshes = this.meshes;
  22675. }
  22676. // Check each mesh
  22677. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  22678. mesh = meshes[meshIndex];
  22679. if (mesh.isBlocked) {
  22680. continue;
  22681. }
  22682. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22683. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  22684. continue;
  22685. }
  22686. mesh.computeWorldMatrix();
  22687. // Intersections
  22688. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22689. this._meshesForIntersections.pushNoDuplicate(mesh);
  22690. }
  22691. // Switch to current LOD
  22692. meshLOD = mesh.getLOD(this.activeCamera);
  22693. if (meshLOD === undefined || meshLOD === null) {
  22694. continue;
  22695. }
  22696. mesh._preActivate();
  22697. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22698. this._activeMeshes.push(mesh);
  22699. this.activeCamera._activeMeshes.push(mesh);
  22700. mesh._activate(this._renderId);
  22701. if (meshLOD !== mesh) {
  22702. meshLOD._activate(this._renderId);
  22703. }
  22704. this._activeMesh(mesh, meshLOD);
  22705. }
  22706. }
  22707. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  22708. // Particle systems
  22709. if (this.particlesEnabled) {
  22710. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  22711. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22712. var particleSystem = this.particleSystems[particleIndex];
  22713. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  22714. continue;
  22715. }
  22716. var emitter = particleSystem.emitter;
  22717. if (!emitter.position || emitter.isEnabled()) {
  22718. this._activeParticleSystems.push(particleSystem);
  22719. particleSystem.animate();
  22720. this._renderingManager.dispatchParticles(particleSystem);
  22721. }
  22722. }
  22723. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22724. }
  22725. };
  22726. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22727. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22728. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22729. mesh.skeleton.prepare();
  22730. }
  22731. if (!mesh.computeBonesUsingShaders) {
  22732. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22733. }
  22734. }
  22735. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22736. var boundingInfo = sourceMesh.getBoundingInfo();
  22737. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22738. }
  22739. if (mesh !== undefined && mesh !== null
  22740. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22741. // Submeshes Octrees
  22742. var len;
  22743. var subMeshes;
  22744. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22745. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22746. len = intersections.length;
  22747. subMeshes = intersections.data;
  22748. }
  22749. else {
  22750. subMeshes = mesh.subMeshes;
  22751. len = subMeshes.length;
  22752. }
  22753. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22754. subMesh = subMeshes[subIndex];
  22755. this._evaluateSubMesh(subMesh, mesh);
  22756. }
  22757. }
  22758. };
  22759. Scene.prototype.updateTransformMatrix = function (force) {
  22760. if (!this.activeCamera) {
  22761. return;
  22762. }
  22763. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22764. };
  22765. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22766. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22767. };
  22768. Scene.prototype._renderForCamera = function (camera) {
  22769. if (camera && camera._skipRendering) {
  22770. return;
  22771. }
  22772. var engine = this._engine;
  22773. this.activeCamera = camera;
  22774. if (!this.activeCamera)
  22775. throw new Error("Active camera not set");
  22776. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22777. // Viewport
  22778. engine.setViewport(this.activeCamera.viewport);
  22779. // Camera
  22780. this.resetCachedMaterial();
  22781. this._renderId++;
  22782. this.activeCamera.update();
  22783. this.updateTransformMatrix();
  22784. if (camera._alternateCamera) {
  22785. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22786. this._alternateRendering = true;
  22787. }
  22788. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22789. // Meshes
  22790. this._evaluateActiveMeshes();
  22791. // Software skinning
  22792. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22793. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22794. mesh.applySkeleton(mesh.skeleton);
  22795. }
  22796. // Render targets
  22797. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22798. var needsRestoreFrameBuffer = false;
  22799. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22800. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22801. }
  22802. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22803. this._intermediateRendering = true;
  22804. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22805. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22806. var renderTarget = this._renderTargets.data[renderIndex];
  22807. if (renderTarget._shouldRender()) {
  22808. this._renderId++;
  22809. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22810. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22811. }
  22812. }
  22813. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22814. this._intermediateRendering = false;
  22815. this._renderId++;
  22816. needsRestoreFrameBuffer = true; // Restore back buffer
  22817. }
  22818. // Render HighlightLayer Texture
  22819. var stencilState = this._engine.getStencilBuffer();
  22820. var renderhighlights = false;
  22821. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22822. this._intermediateRendering = true;
  22823. for (var i = 0; i < this.highlightLayers.length; i++) {
  22824. var highlightLayer = this.highlightLayers[i];
  22825. if (highlightLayer.shouldRender() &&
  22826. (!highlightLayer.camera ||
  22827. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22828. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22829. renderhighlights = true;
  22830. var renderTarget = highlightLayer._mainTexture;
  22831. if (renderTarget._shouldRender()) {
  22832. this._renderId++;
  22833. renderTarget.render(false, false);
  22834. needsRestoreFrameBuffer = true;
  22835. }
  22836. }
  22837. }
  22838. this._intermediateRendering = false;
  22839. this._renderId++;
  22840. }
  22841. if (needsRestoreFrameBuffer) {
  22842. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22843. }
  22844. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22845. // Prepare Frame
  22846. this.postProcessManager._prepareFrame();
  22847. // Backgrounds
  22848. var layerIndex;
  22849. var layer;
  22850. if (this.layers.length) {
  22851. engine.setDepthBuffer(false);
  22852. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22853. layer = this.layers[layerIndex];
  22854. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22855. layer.render();
  22856. }
  22857. }
  22858. engine.setDepthBuffer(true);
  22859. }
  22860. // Activate HighlightLayer stencil
  22861. if (renderhighlights) {
  22862. this._engine.setStencilBuffer(true);
  22863. }
  22864. // Render
  22865. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22866. this._renderingManager.render(null, null, true, true);
  22867. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22868. // Restore HighlightLayer stencil
  22869. if (renderhighlights) {
  22870. this._engine.setStencilBuffer(stencilState);
  22871. }
  22872. // Bounding boxes
  22873. if (this._boundingBoxRenderer) {
  22874. this._boundingBoxRenderer.render();
  22875. }
  22876. // Lens flares
  22877. if (this.lensFlaresEnabled) {
  22878. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22879. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22880. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22881. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22882. lensFlareSystem.render();
  22883. }
  22884. }
  22885. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22886. }
  22887. // Foregrounds
  22888. if (this.layers.length) {
  22889. engine.setDepthBuffer(false);
  22890. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22891. layer = this.layers[layerIndex];
  22892. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22893. layer.render();
  22894. }
  22895. }
  22896. engine.setDepthBuffer(true);
  22897. }
  22898. // Highlight Layer
  22899. if (renderhighlights) {
  22900. engine.setDepthBuffer(false);
  22901. for (var i = 0; i < this.highlightLayers.length; i++) {
  22902. if (this.highlightLayers[i].shouldRender()) {
  22903. this.highlightLayers[i].render();
  22904. }
  22905. }
  22906. engine.setDepthBuffer(true);
  22907. }
  22908. // Finalize frame
  22909. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22910. // Reset some special arrays
  22911. this._renderTargets.reset();
  22912. this._alternateRendering = false;
  22913. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22914. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22915. };
  22916. Scene.prototype._processSubCameras = function (camera) {
  22917. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22918. this._renderForCamera(camera);
  22919. return;
  22920. }
  22921. // Update camera
  22922. if (this.activeCamera) {
  22923. this.activeCamera.update();
  22924. }
  22925. // rig cameras
  22926. for (var index = 0; index < camera._rigCameras.length; index++) {
  22927. this._renderForCamera(camera._rigCameras[index]);
  22928. }
  22929. this.activeCamera = camera;
  22930. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22931. };
  22932. Scene.prototype._checkIntersections = function () {
  22933. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22934. var sourceMesh = this._meshesForIntersections.data[index];
  22935. if (!sourceMesh.actionManager) {
  22936. continue;
  22937. }
  22938. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22939. var action = sourceMesh.actionManager.actions[actionIndex];
  22940. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22941. var parameters = action.getTriggerParameter();
  22942. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22943. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22944. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22945. if (areIntersecting && currentIntersectionInProgress === -1) {
  22946. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22947. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22948. sourceMesh._intersectionsInProgress.push(otherMesh);
  22949. }
  22950. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22951. sourceMesh._intersectionsInProgress.push(otherMesh);
  22952. }
  22953. }
  22954. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22955. //They intersected, and now they don't.
  22956. //is this trigger an exit trigger? execute an event.
  22957. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22958. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22959. }
  22960. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22961. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22962. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22963. }
  22964. }
  22965. }
  22966. }
  22967. }
  22968. };
  22969. Scene.prototype.render = function () {
  22970. if (this.isDisposed) {
  22971. return;
  22972. }
  22973. this._activeParticles.fetchNewFrame();
  22974. this._totalVertices.fetchNewFrame();
  22975. this._activeIndices.fetchNewFrame();
  22976. this._activeBones.fetchNewFrame();
  22977. this._meshesForIntersections.reset();
  22978. this.resetCachedMaterial();
  22979. this.onBeforeAnimationsObservable.notifyObservers(this);
  22980. // Actions
  22981. if (this.actionManager) {
  22982. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22983. }
  22984. //Simplification Queue
  22985. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22986. this.simplificationQueue.executeNext();
  22987. }
  22988. if (this._engine.isDeterministicLockStep()) {
  22989. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22990. var defaultFPS = (60.0 / 1000.0);
  22991. var defaultFrameTime = 1000 / 60; // frame time in MS
  22992. if (this._physicsEngine) {
  22993. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22994. }
  22995. var stepsTaken = 0;
  22996. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22997. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22998. internalSteps = Math.min(internalSteps, maxSubSteps);
  22999. do {
  23000. this.onBeforeStepObservable.notifyObservers(this);
  23001. // Animations
  23002. this._animationRatio = defaultFrameTime * defaultFPS;
  23003. this._animate();
  23004. this.onAfterAnimationsObservable.notifyObservers(this);
  23005. // Physics
  23006. if (this._physicsEngine) {
  23007. this.onBeforePhysicsObservable.notifyObservers(this);
  23008. this._physicsEngine._step(defaultFrameTime / 1000);
  23009. this.onAfterPhysicsObservable.notifyObservers(this);
  23010. }
  23011. this.onAfterStepObservable.notifyObservers(this);
  23012. this._currentStepId++;
  23013. stepsTaken++;
  23014. deltaTime -= defaultFrameTime;
  23015. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23016. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23017. }
  23018. else {
  23019. // Animations
  23020. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23021. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23022. this._animate();
  23023. this.onAfterAnimationsObservable.notifyObservers(this);
  23024. // Physics
  23025. if (this._physicsEngine) {
  23026. this.onBeforePhysicsObservable.notifyObservers(this);
  23027. this._physicsEngine._step(deltaTime / 1000.0);
  23028. this.onAfterPhysicsObservable.notifyObservers(this);
  23029. }
  23030. }
  23031. // update gamepad manager
  23032. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23033. this._gamepadManager._checkGamepadsStatus();
  23034. }
  23035. // Before render
  23036. this.onBeforeRenderObservable.notifyObservers(this);
  23037. // Customs render targets
  23038. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23039. var engine = this.getEngine();
  23040. var currentActiveCamera = this.activeCamera;
  23041. if (this.renderTargetsEnabled) {
  23042. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23043. this._intermediateRendering = true;
  23044. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23045. var renderTarget = this.customRenderTargets[customIndex];
  23046. if (renderTarget._shouldRender()) {
  23047. this._renderId++;
  23048. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23049. if (!this.activeCamera)
  23050. throw new Error("Active camera not set");
  23051. // Viewport
  23052. engine.setViewport(this.activeCamera.viewport);
  23053. // Camera
  23054. this.updateTransformMatrix();
  23055. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23056. }
  23057. }
  23058. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23059. this._intermediateRendering = false;
  23060. this._renderId++;
  23061. }
  23062. // Restore back buffer
  23063. if (this.customRenderTargets.length > 0) {
  23064. engine.restoreDefaultFramebuffer();
  23065. }
  23066. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23067. this.activeCamera = currentActiveCamera;
  23068. // Procedural textures
  23069. if (this.proceduralTexturesEnabled) {
  23070. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23071. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23072. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23073. if (proceduralTexture._shouldRender()) {
  23074. proceduralTexture.render();
  23075. }
  23076. }
  23077. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23078. }
  23079. // Clear
  23080. if (this.autoClearDepthAndStencil || this.autoClear) {
  23081. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23082. }
  23083. // Shadows
  23084. if (this.shadowsEnabled) {
  23085. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23086. var light = this.lights[lightIndex];
  23087. var shadowGenerator = light.getShadowGenerator();
  23088. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  23089. var shadowMap = (shadowGenerator.getShadowMap());
  23090. if (this.textures.indexOf(shadowMap) !== -1) {
  23091. this._renderTargets.push(shadowMap);
  23092. }
  23093. }
  23094. }
  23095. }
  23096. // Depth renderer
  23097. if (this._depthRenderer) {
  23098. this._renderTargets.push(this._depthRenderer.getDepthMap());
  23099. }
  23100. // Geometry renderer
  23101. if (this._geometryBufferRenderer) {
  23102. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  23103. }
  23104. // RenderPipeline
  23105. if (this._postProcessRenderPipelineManager) {
  23106. this._postProcessRenderPipelineManager.update();
  23107. }
  23108. // Multi-cameras?
  23109. if (this.activeCameras.length > 0) {
  23110. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23111. if (cameraIndex > 0) {
  23112. this._engine.clear(null, false, true, true);
  23113. }
  23114. this._processSubCameras(this.activeCameras[cameraIndex]);
  23115. }
  23116. }
  23117. else {
  23118. if (!this.activeCamera) {
  23119. throw new Error("No camera defined");
  23120. }
  23121. this._processSubCameras(this.activeCamera);
  23122. }
  23123. // Intersection checks
  23124. this._checkIntersections();
  23125. // Update the audio listener attached to the camera
  23126. if (BABYLON.AudioEngine) {
  23127. this._updateAudioParameters();
  23128. }
  23129. // After render
  23130. if (this.afterRender) {
  23131. this.afterRender();
  23132. }
  23133. this.onAfterRenderObservable.notifyObservers(this);
  23134. // Cleaning
  23135. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23136. var data = this._toBeDisposed.data[index];
  23137. if (data) {
  23138. data.dispose();
  23139. }
  23140. this._toBeDisposed[index] = null;
  23141. }
  23142. this._toBeDisposed.reset();
  23143. if (this.dumpNextRenderTargets) {
  23144. this.dumpNextRenderTargets = false;
  23145. }
  23146. this._activeBones.addCount(0, true);
  23147. this._activeIndices.addCount(0, true);
  23148. this._activeParticles.addCount(0, true);
  23149. };
  23150. Scene.prototype._updateAudioParameters = function () {
  23151. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23152. return;
  23153. }
  23154. var listeningCamera;
  23155. var audioEngine = BABYLON.Engine.audioEngine;
  23156. if (this.activeCameras.length > 0) {
  23157. listeningCamera = this.activeCameras[0];
  23158. }
  23159. else {
  23160. listeningCamera = this.activeCamera;
  23161. }
  23162. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23163. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23164. // for VR cameras
  23165. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23166. listeningCamera = listeningCamera.rigCameras[0];
  23167. }
  23168. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23169. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23170. cameraDirection.normalize();
  23171. // To avoid some errors on GearVR
  23172. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23173. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23174. }
  23175. var i;
  23176. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23177. var sound = this.mainSoundTrack.soundCollection[i];
  23178. if (sound.useCustomAttenuation) {
  23179. sound.updateDistanceFromListener();
  23180. }
  23181. }
  23182. for (i = 0; i < this.soundTracks.length; i++) {
  23183. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23184. sound = this.soundTracks[i].soundCollection[j];
  23185. if (sound.useCustomAttenuation) {
  23186. sound.updateDistanceFromListener();
  23187. }
  23188. }
  23189. }
  23190. }
  23191. };
  23192. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23193. // Audio
  23194. get: function () {
  23195. return this._audioEnabled;
  23196. },
  23197. set: function (value) {
  23198. this._audioEnabled = value;
  23199. if (BABYLON.AudioEngine) {
  23200. if (this._audioEnabled) {
  23201. this._enableAudio();
  23202. }
  23203. else {
  23204. this._disableAudio();
  23205. }
  23206. }
  23207. },
  23208. enumerable: true,
  23209. configurable: true
  23210. });
  23211. Scene.prototype._disableAudio = function () {
  23212. var i;
  23213. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23214. this.mainSoundTrack.soundCollection[i].pause();
  23215. }
  23216. for (i = 0; i < this.soundTracks.length; i++) {
  23217. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23218. this.soundTracks[i].soundCollection[j].pause();
  23219. }
  23220. }
  23221. };
  23222. Scene.prototype._enableAudio = function () {
  23223. var i;
  23224. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23225. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  23226. this.mainSoundTrack.soundCollection[i].play();
  23227. }
  23228. }
  23229. for (i = 0; i < this.soundTracks.length; i++) {
  23230. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23231. if (this.soundTracks[i].soundCollection[j].isPaused) {
  23232. this.soundTracks[i].soundCollection[j].play();
  23233. }
  23234. }
  23235. }
  23236. };
  23237. Object.defineProperty(Scene.prototype, "headphone", {
  23238. get: function () {
  23239. return this._headphone;
  23240. },
  23241. set: function (value) {
  23242. this._headphone = value;
  23243. if (BABYLON.AudioEngine) {
  23244. if (this._headphone) {
  23245. this._switchAudioModeForHeadphones();
  23246. }
  23247. else {
  23248. this._switchAudioModeForNormalSpeakers();
  23249. }
  23250. }
  23251. },
  23252. enumerable: true,
  23253. configurable: true
  23254. });
  23255. Scene.prototype._switchAudioModeForHeadphones = function () {
  23256. this.mainSoundTrack.switchPanningModelToHRTF();
  23257. for (var i = 0; i < this.soundTracks.length; i++) {
  23258. this.soundTracks[i].switchPanningModelToHRTF();
  23259. }
  23260. };
  23261. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23262. this.mainSoundTrack.switchPanningModelToEqualPower();
  23263. for (var i = 0; i < this.soundTracks.length; i++) {
  23264. this.soundTracks[i].switchPanningModelToEqualPower();
  23265. }
  23266. };
  23267. Scene.prototype.enableDepthRenderer = function () {
  23268. if (this._depthRenderer) {
  23269. return this._depthRenderer;
  23270. }
  23271. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23272. return this._depthRenderer;
  23273. };
  23274. Scene.prototype.disableDepthRenderer = function () {
  23275. if (!this._depthRenderer) {
  23276. return;
  23277. }
  23278. this._depthRenderer.dispose();
  23279. this._depthRenderer = null;
  23280. };
  23281. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23282. if (ratio === void 0) { ratio = 1; }
  23283. if (this._geometryBufferRenderer) {
  23284. return this._geometryBufferRenderer;
  23285. }
  23286. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23287. if (!this._geometryBufferRenderer.isSupported) {
  23288. this._geometryBufferRenderer = null;
  23289. }
  23290. return this._geometryBufferRenderer;
  23291. };
  23292. Scene.prototype.disableGeometryBufferRenderer = function () {
  23293. if (!this._geometryBufferRenderer) {
  23294. return;
  23295. }
  23296. this._geometryBufferRenderer.dispose();
  23297. this._geometryBufferRenderer = null;
  23298. };
  23299. Scene.prototype.freezeMaterials = function () {
  23300. for (var i = 0; i < this.materials.length; i++) {
  23301. this.materials[i].freeze();
  23302. }
  23303. };
  23304. Scene.prototype.unfreezeMaterials = function () {
  23305. for (var i = 0; i < this.materials.length; i++) {
  23306. this.materials[i].unfreeze();
  23307. }
  23308. };
  23309. Scene.prototype.dispose = function () {
  23310. this.beforeRender = null;
  23311. this.afterRender = null;
  23312. this.skeletons = [];
  23313. this.morphTargetManagers = [];
  23314. this.importedMeshesFiles = new Array();
  23315. this.stopAllAnimations();
  23316. this.resetCachedMaterial();
  23317. if (this._depthRenderer) {
  23318. this._depthRenderer.dispose();
  23319. }
  23320. if (this._gamepadManager) {
  23321. this._gamepadManager.dispose();
  23322. this._gamepadManager = null;
  23323. }
  23324. // Smart arrays
  23325. if (this.activeCamera) {
  23326. this.activeCamera._activeMeshes.dispose();
  23327. this.activeCamera = null;
  23328. }
  23329. this._activeMeshes.dispose();
  23330. this._renderingManager.dispose();
  23331. this._processedMaterials.dispose();
  23332. this._activeParticleSystems.dispose();
  23333. this._activeSkeletons.dispose();
  23334. this._softwareSkinnedMeshes.dispose();
  23335. this._renderTargets.dispose();
  23336. if (this._boundingBoxRenderer) {
  23337. this._boundingBoxRenderer.dispose();
  23338. }
  23339. this._meshesForIntersections.dispose();
  23340. this._toBeDisposed.dispose();
  23341. // Abort active requests
  23342. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  23343. var request = _a[_i];
  23344. request.abort();
  23345. }
  23346. // Debug layer
  23347. if (this._debugLayer) {
  23348. this._debugLayer.hide();
  23349. }
  23350. // Events
  23351. this.onDisposeObservable.notifyObservers(this);
  23352. this.onDisposeObservable.clear();
  23353. this.onBeforeRenderObservable.clear();
  23354. this.onAfterRenderObservable.clear();
  23355. this.OnBeforeRenderTargetsRenderObservable.clear();
  23356. this.OnAfterRenderTargetsRenderObservable.clear();
  23357. this.onAfterStepObservable.clear();
  23358. this.onBeforeStepObservable.clear();
  23359. this.onBeforeActiveMeshesEvaluationObservable.clear();
  23360. this.onAfterActiveMeshesEvaluationObservable.clear();
  23361. this.onBeforeParticlesRenderingObservable.clear();
  23362. this.onAfterParticlesRenderingObservable.clear();
  23363. this.onBeforeSpritesRenderingObservable.clear();
  23364. this.onAfterSpritesRenderingObservable.clear();
  23365. this.onBeforeDrawPhaseObservable.clear();
  23366. this.onAfterDrawPhaseObservable.clear();
  23367. this.onBeforePhysicsObservable.clear();
  23368. this.onAfterPhysicsObservable.clear();
  23369. this.onBeforeAnimationsObservable.clear();
  23370. this.onAfterAnimationsObservable.clear();
  23371. this.onDataLoadedObservable.clear();
  23372. this.detachControl();
  23373. // Release sounds & sounds tracks
  23374. if (BABYLON.AudioEngine) {
  23375. this.disposeSounds();
  23376. }
  23377. // VR Helper
  23378. if (this.VRHelper) {
  23379. this.VRHelper.dispose();
  23380. }
  23381. // Detach cameras
  23382. var canvas = this._engine.getRenderingCanvas();
  23383. if (canvas) {
  23384. var index;
  23385. for (index = 0; index < this.cameras.length; index++) {
  23386. this.cameras[index].detachControl(canvas);
  23387. }
  23388. }
  23389. // Release animation groups
  23390. while (this.animationGroups.length) {
  23391. this.animationGroups[0].dispose();
  23392. }
  23393. // Release lights
  23394. while (this.lights.length) {
  23395. this.lights[0].dispose();
  23396. }
  23397. // Release meshes
  23398. while (this.meshes.length) {
  23399. this.meshes[0].dispose(true);
  23400. }
  23401. while (this.transformNodes.length) {
  23402. this.removeTransformNode(this.transformNodes[0]);
  23403. }
  23404. // Release cameras
  23405. while (this.cameras.length) {
  23406. this.cameras[0].dispose();
  23407. }
  23408. // Release materials
  23409. if (this.defaultMaterial) {
  23410. this.defaultMaterial.dispose();
  23411. }
  23412. while (this.multiMaterials.length) {
  23413. this.multiMaterials[0].dispose();
  23414. }
  23415. while (this.materials.length) {
  23416. this.materials[0].dispose();
  23417. }
  23418. // Release particles
  23419. while (this.particleSystems.length) {
  23420. this.particleSystems[0].dispose();
  23421. }
  23422. // Release sprites
  23423. while (this.spriteManagers.length) {
  23424. this.spriteManagers[0].dispose();
  23425. }
  23426. // Release postProcesses
  23427. while (this.postProcesses.length) {
  23428. this.postProcesses[0].dispose();
  23429. }
  23430. // Release layers
  23431. while (this.layers.length) {
  23432. this.layers[0].dispose();
  23433. }
  23434. while (this.highlightLayers.length) {
  23435. this.highlightLayers[0].dispose();
  23436. }
  23437. // Release textures
  23438. while (this.textures.length) {
  23439. this.textures[0].dispose();
  23440. }
  23441. // Release UBO
  23442. this._sceneUbo.dispose();
  23443. if (this._alternateSceneUbo) {
  23444. this._alternateSceneUbo.dispose();
  23445. }
  23446. // Post-processes
  23447. this.postProcessManager.dispose();
  23448. if (this._postProcessRenderPipelineManager) {
  23449. this._postProcessRenderPipelineManager.dispose();
  23450. }
  23451. // Physics
  23452. if (this._physicsEngine) {
  23453. this.disablePhysicsEngine();
  23454. }
  23455. // Remove from engine
  23456. index = this._engine.scenes.indexOf(this);
  23457. if (index > -1) {
  23458. this._engine.scenes.splice(index, 1);
  23459. }
  23460. this._engine.wipeCaches(true);
  23461. this._isDisposed = true;
  23462. };
  23463. Object.defineProperty(Scene.prototype, "isDisposed", {
  23464. get: function () {
  23465. return this._isDisposed;
  23466. },
  23467. enumerable: true,
  23468. configurable: true
  23469. });
  23470. // Release sounds & sounds tracks
  23471. Scene.prototype.disposeSounds = function () {
  23472. if (!this._mainSoundTrack) {
  23473. return;
  23474. }
  23475. this.mainSoundTrack.dispose();
  23476. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  23477. this.soundTracks[scIndex].dispose();
  23478. }
  23479. };
  23480. // Octrees
  23481. Scene.prototype.getWorldExtends = function () {
  23482. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23483. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  23484. for (var index = 0; index < this.meshes.length; index++) {
  23485. var mesh = this.meshes[index];
  23486. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  23487. continue;
  23488. }
  23489. mesh.computeWorldMatrix(true);
  23490. var boundingInfo = mesh.getBoundingInfo();
  23491. var minBox = boundingInfo.boundingBox.minimumWorld;
  23492. var maxBox = boundingInfo.boundingBox.maximumWorld;
  23493. BABYLON.Tools.CheckExtends(minBox, min, max);
  23494. BABYLON.Tools.CheckExtends(maxBox, min, max);
  23495. }
  23496. return {
  23497. min: min,
  23498. max: max
  23499. };
  23500. };
  23501. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  23502. if (maxCapacity === void 0) { maxCapacity = 64; }
  23503. if (maxDepth === void 0) { maxDepth = 2; }
  23504. if (!this._selectionOctree) {
  23505. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  23506. }
  23507. var worldExtends = this.getWorldExtends();
  23508. // Update octree
  23509. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  23510. return this._selectionOctree;
  23511. };
  23512. // Picking
  23513. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  23514. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23515. var result = BABYLON.Ray.Zero();
  23516. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  23517. return result;
  23518. };
  23519. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  23520. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23521. var engine = this._engine;
  23522. if (!camera) {
  23523. if (!this.activeCamera)
  23524. throw new Error("Active camera not set");
  23525. camera = this.activeCamera;
  23526. }
  23527. var cameraViewport = camera.viewport;
  23528. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23529. // Moving coordinates to local viewport world
  23530. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23531. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23532. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  23533. return this;
  23534. };
  23535. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  23536. var result = BABYLON.Ray.Zero();
  23537. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  23538. return result;
  23539. };
  23540. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  23541. if (!BABYLON.PickingInfo) {
  23542. return this;
  23543. }
  23544. var engine = this._engine;
  23545. if (!camera) {
  23546. if (!this.activeCamera)
  23547. throw new Error("Active camera not set");
  23548. camera = this.activeCamera;
  23549. }
  23550. var cameraViewport = camera.viewport;
  23551. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23552. var identity = BABYLON.Matrix.Identity();
  23553. // Moving coordinates to local viewport world
  23554. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23555. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23556. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  23557. return this;
  23558. };
  23559. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  23560. if (!BABYLON.PickingInfo) {
  23561. return null;
  23562. }
  23563. var pickingInfo = null;
  23564. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23565. var mesh = this.meshes[meshIndex];
  23566. if (predicate) {
  23567. if (!predicate(mesh)) {
  23568. continue;
  23569. }
  23570. }
  23571. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23572. continue;
  23573. }
  23574. var world = mesh.getWorldMatrix();
  23575. var ray = rayFunction(world);
  23576. var result = mesh.intersects(ray, fastCheck);
  23577. if (!result || !result.hit)
  23578. continue;
  23579. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23580. continue;
  23581. pickingInfo = result;
  23582. if (fastCheck) {
  23583. break;
  23584. }
  23585. }
  23586. return pickingInfo || new BABYLON.PickingInfo();
  23587. };
  23588. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  23589. if (!BABYLON.PickingInfo) {
  23590. return null;
  23591. }
  23592. var pickingInfos = new Array();
  23593. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23594. var mesh = this.meshes[meshIndex];
  23595. if (predicate) {
  23596. if (!predicate(mesh)) {
  23597. continue;
  23598. }
  23599. }
  23600. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23601. continue;
  23602. }
  23603. var world = mesh.getWorldMatrix();
  23604. var ray = rayFunction(world);
  23605. var result = mesh.intersects(ray, false);
  23606. if (!result || !result.hit)
  23607. continue;
  23608. pickingInfos.push(result);
  23609. }
  23610. return pickingInfos;
  23611. };
  23612. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23613. if (!BABYLON.PickingInfo) {
  23614. return null;
  23615. }
  23616. var pickingInfo = null;
  23617. if (!camera) {
  23618. if (!this.activeCamera) {
  23619. return null;
  23620. }
  23621. camera = this.activeCamera;
  23622. }
  23623. if (this.spriteManagers.length > 0) {
  23624. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23625. var spriteManager = this.spriteManagers[spriteIndex];
  23626. if (!spriteManager.isPickable) {
  23627. continue;
  23628. }
  23629. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23630. if (!result || !result.hit)
  23631. continue;
  23632. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23633. continue;
  23634. pickingInfo = result;
  23635. if (fastCheck) {
  23636. break;
  23637. }
  23638. }
  23639. }
  23640. return pickingInfo || new BABYLON.PickingInfo();
  23641. };
  23642. /** Launch a ray to try to pick a mesh in the scene
  23643. * @param x position on screen
  23644. * @param y position on screen
  23645. * @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
  23646. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23647. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23648. */
  23649. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23650. var _this = this;
  23651. if (!BABYLON.PickingInfo) {
  23652. return null;
  23653. }
  23654. return this._internalPick(function (world) {
  23655. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  23656. return _this._tempPickingRay;
  23657. }, predicate, fastCheck);
  23658. };
  23659. /** Launch a ray to try to pick a sprite in the scene
  23660. * @param x position on screen
  23661. * @param y position on screen
  23662. * @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
  23663. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23664. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23665. */
  23666. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23667. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  23668. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  23669. };
  23670. /** Use the given ray to pick a mesh in the scene
  23671. * @param ray The ray to use to pick meshes
  23672. * @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
  23673. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23674. */
  23675. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23676. var _this = this;
  23677. return this._internalPick(function (world) {
  23678. if (!_this._pickWithRayInverseMatrix) {
  23679. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23680. }
  23681. world.invertToRef(_this._pickWithRayInverseMatrix);
  23682. if (!_this._cachedRayForTransform) {
  23683. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23684. }
  23685. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23686. return _this._cachedRayForTransform;
  23687. }, predicate, fastCheck);
  23688. };
  23689. /**
  23690. * Launch a ray to try to pick a mesh in the scene
  23691. * @param x X position on screen
  23692. * @param y Y position on screen
  23693. * @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
  23694. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23695. */
  23696. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23697. var _this = this;
  23698. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  23699. };
  23700. /**
  23701. * Launch a ray to try to pick a mesh in the scene
  23702. * @param ray Ray to use
  23703. * @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
  23704. */
  23705. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23706. var _this = this;
  23707. return this._internalMultiPick(function (world) {
  23708. if (!_this._pickWithRayInverseMatrix) {
  23709. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23710. }
  23711. world.invertToRef(_this._pickWithRayInverseMatrix);
  23712. if (!_this._cachedRayForTransform) {
  23713. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23714. }
  23715. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23716. return _this._cachedRayForTransform;
  23717. }, predicate);
  23718. };
  23719. Scene.prototype.setPointerOverMesh = function (mesh) {
  23720. if (this._pointerOverMesh === mesh) {
  23721. return;
  23722. }
  23723. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23724. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23725. }
  23726. this._pointerOverMesh = mesh;
  23727. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23728. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23729. }
  23730. };
  23731. Scene.prototype.getPointerOverMesh = function () {
  23732. return this._pointerOverMesh;
  23733. };
  23734. Scene.prototype.setPointerOverSprite = function (sprite) {
  23735. if (this._pointerOverSprite === sprite) {
  23736. return;
  23737. }
  23738. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23739. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23740. }
  23741. this._pointerOverSprite = sprite;
  23742. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23743. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23744. }
  23745. };
  23746. Scene.prototype.getPointerOverSprite = function () {
  23747. return this._pointerOverSprite;
  23748. };
  23749. // Physics
  23750. Scene.prototype.getPhysicsEngine = function () {
  23751. return this._physicsEngine;
  23752. };
  23753. /**
  23754. * Enables physics to the current scene
  23755. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23756. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23757. * @return {boolean} was the physics engine initialized
  23758. */
  23759. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23760. if (gravity === void 0) { gravity = null; }
  23761. if (this._physicsEngine) {
  23762. return true;
  23763. }
  23764. try {
  23765. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23766. return true;
  23767. }
  23768. catch (e) {
  23769. BABYLON.Tools.Error(e.message);
  23770. return false;
  23771. }
  23772. };
  23773. Scene.prototype.disablePhysicsEngine = function () {
  23774. if (!this._physicsEngine) {
  23775. return;
  23776. }
  23777. this._physicsEngine.dispose();
  23778. this._physicsEngine = null;
  23779. };
  23780. Scene.prototype.isPhysicsEnabled = function () {
  23781. return this._physicsEngine !== undefined;
  23782. };
  23783. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23784. var mesh = compound.parts[0].mesh;
  23785. if (mesh.physicsImpostor) {
  23786. mesh.physicsImpostor.dispose();
  23787. mesh.physicsImpostor = null;
  23788. }
  23789. };
  23790. // Misc.
  23791. Scene.prototype._rebuildGeometries = function () {
  23792. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23793. var geometry = _a[_i];
  23794. geometry._rebuild();
  23795. }
  23796. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23797. var mesh = _c[_b];
  23798. mesh._rebuild();
  23799. }
  23800. if (this.postProcessManager) {
  23801. this.postProcessManager._rebuild();
  23802. }
  23803. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23804. var layer = _e[_d];
  23805. layer._rebuild();
  23806. }
  23807. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23808. var highlightLayer = _g[_f];
  23809. highlightLayer._rebuild();
  23810. }
  23811. if (this._boundingBoxRenderer) {
  23812. this._boundingBoxRenderer._rebuild();
  23813. }
  23814. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23815. var system = _j[_h];
  23816. system.rebuild();
  23817. }
  23818. if (this._postProcessRenderPipelineManager) {
  23819. this._postProcessRenderPipelineManager._rebuild();
  23820. }
  23821. };
  23822. Scene.prototype._rebuildTextures = function () {
  23823. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23824. var texture = _a[_i];
  23825. texture._rebuild();
  23826. }
  23827. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23828. };
  23829. /**
  23830. * Creates a default light for the scene.
  23831. * @param replace Whether to replace the existing lights in the scene.
  23832. */
  23833. Scene.prototype.createDefaultLight = function (replace) {
  23834. if (replace === void 0) { replace = false; }
  23835. // Dispose existing light in replace mode.
  23836. if (replace) {
  23837. if (this.lights) {
  23838. for (var i = 0; i < this.lights.length; i++) {
  23839. this.lights[i].dispose();
  23840. }
  23841. }
  23842. }
  23843. // Light
  23844. if (this.lights.length === 0) {
  23845. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23846. }
  23847. };
  23848. /**
  23849. * Creates a default camera for the scene.
  23850. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  23851. * @param replace Whether to replace the existing active camera in the scene.
  23852. * @param attachCameraControls Whether to attach camera controls to the canvas.
  23853. */
  23854. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  23855. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23856. if (replace === void 0) { replace = false; }
  23857. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23858. // Dispose existing camera in replace mode.
  23859. if (replace) {
  23860. if (this.activeCamera) {
  23861. this.activeCamera.dispose();
  23862. this.activeCamera = null;
  23863. }
  23864. }
  23865. // Camera
  23866. if (!this.activeCamera) {
  23867. var worldExtends = this.getWorldExtends();
  23868. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23869. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23870. var camera;
  23871. var radius = worldSize.length() * 1.5;
  23872. if (createArcRotateCamera) {
  23873. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23874. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23875. arcRotateCamera.wheelPrecision = 100 / radius;
  23876. camera = arcRotateCamera;
  23877. }
  23878. else {
  23879. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23880. freeCamera.setTarget(worldCenter);
  23881. camera = freeCamera;
  23882. }
  23883. camera.minZ = radius * 0.01;
  23884. camera.maxZ = radius * 1000;
  23885. camera.speed = radius * 0.2;
  23886. this.activeCamera = camera;
  23887. var canvas = this.getEngine().getRenderingCanvas();
  23888. if (attachCameraControls && canvas) {
  23889. camera.attachControl(canvas);
  23890. }
  23891. }
  23892. };
  23893. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23894. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23895. if (replace === void 0) { replace = false; }
  23896. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23897. this.createDefaultLight(replace);
  23898. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  23899. };
  23900. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23901. if (pbr === void 0) { pbr = false; }
  23902. if (scale === void 0) { scale = 1000; }
  23903. if (blur === void 0) { blur = 0; }
  23904. if (environmentTexture) {
  23905. this.environmentTexture = environmentTexture;
  23906. }
  23907. if (!this.environmentTexture) {
  23908. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23909. return null;
  23910. }
  23911. // Skybox
  23912. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23913. if (pbr) {
  23914. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23915. hdrSkyboxMaterial.backFaceCulling = false;
  23916. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23917. if (hdrSkyboxMaterial.reflectionTexture) {
  23918. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23919. }
  23920. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23921. hdrSkyboxMaterial.disableLighting = true;
  23922. hdrSkyboxMaterial.twoSidedLighting = true;
  23923. hdrSkybox.infiniteDistance = true;
  23924. hdrSkybox.material = hdrSkyboxMaterial;
  23925. }
  23926. else {
  23927. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23928. skyboxMaterial.backFaceCulling = false;
  23929. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23930. if (skyboxMaterial.reflectionTexture) {
  23931. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23932. }
  23933. skyboxMaterial.disableLighting = true;
  23934. hdrSkybox.infiniteDistance = true;
  23935. hdrSkybox.material = skyboxMaterial;
  23936. }
  23937. return hdrSkybox;
  23938. };
  23939. Scene.prototype.createDefaultEnvironment = function (options) {
  23940. if (BABYLON.EnvironmentHelper) {
  23941. return new BABYLON.EnvironmentHelper(options, this);
  23942. }
  23943. return null;
  23944. };
  23945. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23946. if (webVROptions === void 0) { webVROptions = {}; }
  23947. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23948. };
  23949. // Tags
  23950. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23951. if (tagsQuery === undefined) {
  23952. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23953. return list;
  23954. }
  23955. var listByTags = [];
  23956. forEach = forEach || (function (item) { return; });
  23957. for (var i in list) {
  23958. var item = list[i];
  23959. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23960. listByTags.push(item);
  23961. forEach(item);
  23962. }
  23963. }
  23964. return listByTags;
  23965. };
  23966. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23967. return this._getByTags(this.meshes, tagsQuery, forEach);
  23968. };
  23969. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23970. return this._getByTags(this.cameras, tagsQuery, forEach);
  23971. };
  23972. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23973. return this._getByTags(this.lights, tagsQuery, forEach);
  23974. };
  23975. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23976. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23977. };
  23978. /**
  23979. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23980. * This allowed control for front to back rendering or reversly depending of the special needs.
  23981. *
  23982. * @param renderingGroupId The rendering group id corresponding to its index
  23983. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23984. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23985. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23986. */
  23987. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23988. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23989. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23990. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23991. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23992. };
  23993. /**
  23994. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23995. *
  23996. * @param renderingGroupId The rendering group id corresponding to its index
  23997. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23998. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23999. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24000. */
  24001. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24002. if (depth === void 0) { depth = true; }
  24003. if (stencil === void 0) { stencil = true; }
  24004. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24005. };
  24006. /**
  24007. * Will flag all materials as dirty to trigger new shader compilation
  24008. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24009. */
  24010. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24011. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24012. var material = _a[_i];
  24013. if (predicate && !predicate(material)) {
  24014. continue;
  24015. }
  24016. material.markAsDirty(flag);
  24017. }
  24018. };
  24019. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24020. var _this = this;
  24021. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24022. this._activeRequests.push(request);
  24023. request.onCompleteObservable.add(function (request) {
  24024. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24025. });
  24026. return request;
  24027. };
  24028. /** @ignore */
  24029. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24030. var _this = this;
  24031. return new Promise(function (resolve, reject) {
  24032. _this._loadFile(url, function (data) {
  24033. resolve(data);
  24034. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24035. reject(exception);
  24036. });
  24037. });
  24038. };
  24039. // Statics
  24040. Scene._FOGMODE_NONE = 0;
  24041. Scene._FOGMODE_EXP = 1;
  24042. Scene._FOGMODE_EXP2 = 2;
  24043. Scene._FOGMODE_LINEAR = 3;
  24044. Scene._uniqueIdCounter = 0;
  24045. Scene.MinDeltaTime = 1.0;
  24046. Scene.MaxDeltaTime = 1000.0;
  24047. /** The distance in pixel that you have to move to prevent some events */
  24048. Scene.DragMovementThreshold = 10; // in pixels
  24049. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24050. Scene.LongPressDelay = 500; // in milliseconds
  24051. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24052. Scene.DoubleClickDelay = 300; // in milliseconds
  24053. /** If you need to check double click without raising a single click at first click, enable this flag */
  24054. Scene.ExclusiveDoubleClickMode = false;
  24055. return Scene;
  24056. }());
  24057. BABYLON.Scene = Scene;
  24058. })(BABYLON || (BABYLON = {}));
  24059. //# sourceMappingURL=babylon.scene.js.map
  24060. var BABYLON;
  24061. (function (BABYLON) {
  24062. /**
  24063. * Set of assets to keep when moving a scene into an asset container.
  24064. */
  24065. var KeepAssets = /** @class */ (function () {
  24066. function KeepAssets() {
  24067. /**
  24068. * Cameras to keep.
  24069. */
  24070. this.cameras = new Array();
  24071. /**
  24072. * Lights to keep.
  24073. */
  24074. this.lights = new Array();
  24075. /**
  24076. * Meshes to keep.
  24077. */
  24078. this.meshes = new Array();
  24079. /**
  24080. * Skeletons to keep.
  24081. */
  24082. this.skeletons = new Array();
  24083. /**
  24084. * ParticleSystems to keep.
  24085. */
  24086. this.particleSystems = new Array();
  24087. /**
  24088. * Animations to keep.
  24089. */
  24090. this.animations = new Array();
  24091. /**
  24092. * MultiMaterials to keep.
  24093. */
  24094. this.multiMaterials = new Array();
  24095. /**
  24096. * Materials to keep.
  24097. */
  24098. this.materials = new Array();
  24099. /**
  24100. * MorphTargetManagers to keep.
  24101. */
  24102. this.morphTargetManagers = new Array();
  24103. /**
  24104. * Geometries to keep.
  24105. */
  24106. this.geometries = new Array();
  24107. /**
  24108. * TransformNodes to keep.
  24109. */
  24110. this.transformNodes = new Array();
  24111. /**
  24112. * LensFlareSystems to keep.
  24113. */
  24114. this.lensFlareSystems = new Array();
  24115. /**
  24116. * ShadowGenerators to keep.
  24117. */
  24118. this.shadowGenerators = new Array();
  24119. /**
  24120. * ActionManagers to keep.
  24121. */
  24122. this.actionManagers = new Array();
  24123. /**
  24124. * Sounds to keep.
  24125. */
  24126. this.sounds = new Array();
  24127. }
  24128. return KeepAssets;
  24129. }());
  24130. BABYLON.KeepAssets = KeepAssets;
  24131. /**
  24132. * Container with a set of assets that can be added or removed from a scene.
  24133. */
  24134. var AssetContainer = /** @class */ (function () {
  24135. /**
  24136. * Instantiates an AssetContainer.
  24137. * @param scene The scene the AssetContainer belongs to.
  24138. */
  24139. function AssetContainer(scene) {
  24140. // Objects
  24141. /**
  24142. * Cameras populated in the container.
  24143. */
  24144. this.cameras = new Array();
  24145. /**
  24146. * Lights populated in the container.
  24147. */
  24148. this.lights = new Array();
  24149. /**
  24150. * Meshes populated in the container.
  24151. */
  24152. this.meshes = new Array();
  24153. /**
  24154. * Skeletons populated in the container.
  24155. */
  24156. this.skeletons = new Array();
  24157. /**
  24158. * ParticleSystems populated in the container.
  24159. */
  24160. this.particleSystems = new Array();
  24161. /**
  24162. * Animations populated in the container.
  24163. */
  24164. this.animations = new Array();
  24165. /**
  24166. * MultiMaterials populated in the container.
  24167. */
  24168. this.multiMaterials = new Array();
  24169. /**
  24170. * Materials populated in the container.
  24171. */
  24172. this.materials = new Array();
  24173. /**
  24174. * MorphTargetManagers populated in the container.
  24175. */
  24176. this.morphTargetManagers = new Array();
  24177. /**
  24178. * Geometries populated in the container.
  24179. */
  24180. this.geometries = new Array();
  24181. /**
  24182. * TransformNodes populated in the container.
  24183. */
  24184. this.transformNodes = new Array();
  24185. /**
  24186. * LensFlareSystems populated in the container.
  24187. */
  24188. this.lensFlareSystems = new Array();
  24189. /**
  24190. * ShadowGenerators populated in the container.
  24191. */
  24192. this.shadowGenerators = new Array();
  24193. /**
  24194. * ActionManagers populated in the container.
  24195. */
  24196. this.actionManagers = new Array();
  24197. /**
  24198. * Sounds populated in the container.
  24199. */
  24200. this.sounds = new Array();
  24201. this.scene = scene;
  24202. }
  24203. /**
  24204. * Adds all the assets from the container to the scene.
  24205. */
  24206. AssetContainer.prototype.addAllToScene = function () {
  24207. var _this = this;
  24208. this.cameras.forEach(function (o) {
  24209. _this.scene.addCamera(o);
  24210. });
  24211. this.lights.forEach(function (o) {
  24212. _this.scene.addLight(o);
  24213. });
  24214. this.meshes.forEach(function (o) {
  24215. _this.scene.addMesh(o);
  24216. });
  24217. this.skeletons.forEach(function (o) {
  24218. _this.scene.addSkeleton(o);
  24219. });
  24220. this.particleSystems.forEach(function (o) {
  24221. _this.scene.addParticleSystem(o);
  24222. });
  24223. this.animations.forEach(function (o) {
  24224. _this.scene.addAnimation(o);
  24225. });
  24226. this.multiMaterials.forEach(function (o) {
  24227. _this.scene.addMultiMaterial(o);
  24228. });
  24229. this.materials.forEach(function (o) {
  24230. _this.scene.addMaterial(o);
  24231. });
  24232. this.morphTargetManagers.forEach(function (o) {
  24233. _this.scene.addMorphTargetManager(o);
  24234. });
  24235. this.geometries.forEach(function (o) {
  24236. _this.scene.addGeometry(o);
  24237. });
  24238. this.transformNodes.forEach(function (o) {
  24239. _this.scene.addTransformNode(o);
  24240. });
  24241. this.lensFlareSystems.forEach(function (o) {
  24242. _this.scene.addLensFlareSystem(o);
  24243. });
  24244. this.actionManagers.forEach(function (o) {
  24245. _this.scene.addActionManager(o);
  24246. });
  24247. this.sounds.forEach(function (o) {
  24248. o.play();
  24249. o.autoplay = true;
  24250. _this.scene.mainSoundTrack.AddSound(o);
  24251. });
  24252. };
  24253. /**
  24254. * Removes all the assets in the container from the scene
  24255. */
  24256. AssetContainer.prototype.removeAllFromScene = function () {
  24257. var _this = this;
  24258. this.cameras.forEach(function (o) {
  24259. _this.scene.removeCamera(o);
  24260. });
  24261. this.lights.forEach(function (o) {
  24262. _this.scene.removeLight(o);
  24263. });
  24264. this.meshes.forEach(function (o) {
  24265. _this.scene.removeMesh(o);
  24266. });
  24267. this.skeletons.forEach(function (o) {
  24268. _this.scene.removeSkeleton(o);
  24269. });
  24270. this.particleSystems.forEach(function (o) {
  24271. _this.scene.removeParticleSystem(o);
  24272. });
  24273. this.animations.forEach(function (o) {
  24274. _this.scene.removeAnimation(o);
  24275. });
  24276. this.multiMaterials.forEach(function (o) {
  24277. _this.scene.removeMultiMaterial(o);
  24278. });
  24279. this.materials.forEach(function (o) {
  24280. _this.scene.removeMaterial(o);
  24281. });
  24282. this.morphTargetManagers.forEach(function (o) {
  24283. _this.scene.removeMorphTargetManager(o);
  24284. });
  24285. this.geometries.forEach(function (o) {
  24286. _this.scene.removeGeometry(o);
  24287. });
  24288. this.transformNodes.forEach(function (o) {
  24289. _this.scene.removeTransformNode(o);
  24290. });
  24291. this.lensFlareSystems.forEach(function (o) {
  24292. _this.scene.removeLensFlareSystem(o);
  24293. });
  24294. this.actionManagers.forEach(function (o) {
  24295. _this.scene.removeActionManager(o);
  24296. });
  24297. this.sounds.forEach(function (o) {
  24298. o.stop();
  24299. o.autoplay = false;
  24300. _this.scene.mainSoundTrack.RemoveSound(o);
  24301. });
  24302. };
  24303. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24304. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24305. var asset = sourceAssets_1[_i];
  24306. var move = true;
  24307. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  24308. var keepAsset = keepAssets_1[_a];
  24309. if (asset === keepAsset) {
  24310. move = false;
  24311. break;
  24312. }
  24313. }
  24314. if (move) {
  24315. targetAssets.push(asset);
  24316. }
  24317. }
  24318. };
  24319. /**
  24320. * Removes all the assets contained in the scene and adds them to the container.
  24321. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  24322. */
  24323. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  24324. if (keepAssets === undefined) {
  24325. keepAssets = new KeepAssets();
  24326. }
  24327. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  24328. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  24329. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  24330. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  24331. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  24332. Array.prototype.push.apply(this.animations, this.scene.animations);
  24333. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  24334. Array.prototype.push.apply(this.lights, this.scene.lights);
  24335. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  24336. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  24337. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  24338. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  24339. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  24340. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  24341. this.removeAllFromScene();
  24342. };
  24343. return AssetContainer;
  24344. }());
  24345. BABYLON.AssetContainer = AssetContainer;
  24346. })(BABYLON || (BABYLON = {}));
  24347. //# sourceMappingURL=babylon.assetContainer.js.map
  24348. var BABYLON;
  24349. (function (BABYLON) {
  24350. var Buffer = /** @class */ (function () {
  24351. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  24352. if (instanced === void 0) { instanced = false; }
  24353. if (engine instanceof BABYLON.Mesh) {
  24354. this._engine = engine.getScene().getEngine();
  24355. }
  24356. else {
  24357. this._engine = engine;
  24358. }
  24359. this._updatable = updatable;
  24360. this._data = data;
  24361. this._strideSize = stride;
  24362. if (!postponeInternalCreation) {
  24363. this.create();
  24364. }
  24365. this._instanced = instanced;
  24366. this._instanceDivisor = instanced ? 1 : 0;
  24367. }
  24368. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  24369. // a lot of these parameters are ignored as they are overriden by the buffer
  24370. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  24371. };
  24372. // Properties
  24373. Buffer.prototype.isUpdatable = function () {
  24374. return this._updatable;
  24375. };
  24376. Buffer.prototype.getData = function () {
  24377. return this._data;
  24378. };
  24379. Buffer.prototype.getBuffer = function () {
  24380. return this._buffer;
  24381. };
  24382. Buffer.prototype.getStrideSize = function () {
  24383. return this._strideSize;
  24384. };
  24385. Buffer.prototype.getIsInstanced = function () {
  24386. return this._instanced;
  24387. };
  24388. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  24389. get: function () {
  24390. return this._instanceDivisor;
  24391. },
  24392. set: function (value) {
  24393. this._instanceDivisor = value;
  24394. if (value == 0) {
  24395. this._instanced = false;
  24396. }
  24397. else {
  24398. this._instanced = true;
  24399. }
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. // Methods
  24405. Buffer.prototype.create = function (data) {
  24406. if (data === void 0) { data = null; }
  24407. if (!data && this._buffer) {
  24408. return; // nothing to do
  24409. }
  24410. data = data || this._data;
  24411. if (!data) {
  24412. return;
  24413. }
  24414. if (!this._buffer) {
  24415. if (this._updatable) {
  24416. this._buffer = this._engine.createDynamicVertexBuffer(data);
  24417. this._data = data;
  24418. }
  24419. else {
  24420. this._buffer = this._engine.createVertexBuffer(data);
  24421. }
  24422. }
  24423. else if (this._updatable) {
  24424. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  24425. this._data = data;
  24426. }
  24427. };
  24428. Buffer.prototype._rebuild = function () {
  24429. this._buffer = null;
  24430. this.create(this._data);
  24431. };
  24432. Buffer.prototype.update = function (data) {
  24433. this.create(data);
  24434. };
  24435. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  24436. if (!this._buffer) {
  24437. return;
  24438. }
  24439. if (this._updatable) {
  24440. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  24441. this._data = null;
  24442. }
  24443. };
  24444. Buffer.prototype.dispose = function () {
  24445. if (!this._buffer) {
  24446. return;
  24447. }
  24448. if (this._engine._releaseBuffer(this._buffer)) {
  24449. this._buffer = null;
  24450. }
  24451. };
  24452. return Buffer;
  24453. }());
  24454. BABYLON.Buffer = Buffer;
  24455. })(BABYLON || (BABYLON = {}));
  24456. //# sourceMappingURL=babylon.buffer.js.map
  24457. var BABYLON;
  24458. (function (BABYLON) {
  24459. var VertexBuffer = /** @class */ (function () {
  24460. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  24461. if (!stride) {
  24462. // Deduce stride from kind
  24463. switch (kind) {
  24464. case VertexBuffer.PositionKind:
  24465. stride = 3;
  24466. break;
  24467. case VertexBuffer.NormalKind:
  24468. stride = 3;
  24469. break;
  24470. case VertexBuffer.UVKind:
  24471. case VertexBuffer.UV2Kind:
  24472. case VertexBuffer.UV3Kind:
  24473. case VertexBuffer.UV4Kind:
  24474. case VertexBuffer.UV5Kind:
  24475. case VertexBuffer.UV6Kind:
  24476. stride = 2;
  24477. break;
  24478. case VertexBuffer.TangentKind:
  24479. case VertexBuffer.ColorKind:
  24480. stride = 4;
  24481. break;
  24482. case VertexBuffer.MatricesIndicesKind:
  24483. case VertexBuffer.MatricesIndicesExtraKind:
  24484. stride = 4;
  24485. break;
  24486. case VertexBuffer.MatricesWeightsKind:
  24487. case VertexBuffer.MatricesWeightsExtraKind:
  24488. default:
  24489. stride = 4;
  24490. break;
  24491. }
  24492. }
  24493. if (data instanceof BABYLON.Buffer) {
  24494. if (!stride) {
  24495. stride = data.getStrideSize();
  24496. }
  24497. this._buffer = data;
  24498. this._ownsBuffer = false;
  24499. }
  24500. else {
  24501. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  24502. this._ownsBuffer = true;
  24503. }
  24504. this._stride = stride;
  24505. this._offset = offset ? offset : 0;
  24506. this._size = size ? size : stride;
  24507. this._kind = kind;
  24508. }
  24509. VertexBuffer.prototype._rebuild = function () {
  24510. if (!this._buffer) {
  24511. return;
  24512. }
  24513. this._buffer._rebuild();
  24514. };
  24515. /**
  24516. * Returns the kind of the VertexBuffer (string).
  24517. */
  24518. VertexBuffer.prototype.getKind = function () {
  24519. return this._kind;
  24520. };
  24521. // Properties
  24522. /**
  24523. * Boolean : is the VertexBuffer updatable ?
  24524. */
  24525. VertexBuffer.prototype.isUpdatable = function () {
  24526. return this._buffer.isUpdatable();
  24527. };
  24528. /**
  24529. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  24530. */
  24531. VertexBuffer.prototype.getData = function () {
  24532. return this._buffer.getData();
  24533. };
  24534. /**
  24535. * Returns the WebGLBuffer associated to the VertexBuffer.
  24536. */
  24537. VertexBuffer.prototype.getBuffer = function () {
  24538. return this._buffer.getBuffer();
  24539. };
  24540. /**
  24541. * Returns the stride of the VertexBuffer (integer).
  24542. */
  24543. VertexBuffer.prototype.getStrideSize = function () {
  24544. return this._stride;
  24545. };
  24546. /**
  24547. * Returns the offset (integer).
  24548. */
  24549. VertexBuffer.prototype.getOffset = function () {
  24550. return this._offset;
  24551. };
  24552. /**
  24553. * Returns the VertexBuffer total size (integer).
  24554. */
  24555. VertexBuffer.prototype.getSize = function () {
  24556. return this._size;
  24557. };
  24558. /**
  24559. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  24560. */
  24561. VertexBuffer.prototype.getIsInstanced = function () {
  24562. return this._buffer.getIsInstanced();
  24563. };
  24564. /**
  24565. * Returns the instancing divisor, zero for non-instanced (integer).
  24566. */
  24567. VertexBuffer.prototype.getInstanceDivisor = function () {
  24568. return this._buffer.instanceDivisor;
  24569. };
  24570. // Methods
  24571. /**
  24572. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  24573. * Returns the created WebGLBuffer.
  24574. */
  24575. VertexBuffer.prototype.create = function (data) {
  24576. return this._buffer.create(data);
  24577. };
  24578. /**
  24579. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24580. * This function will create a new buffer if the current one is not updatable
  24581. * Returns the updated WebGLBuffer.
  24582. */
  24583. VertexBuffer.prototype.update = function (data) {
  24584. return this._buffer.update(data);
  24585. };
  24586. /**
  24587. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24588. * Returns the directly updated WebGLBuffer.
  24589. */
  24590. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  24591. return this._buffer.updateDirectly(data, offset);
  24592. };
  24593. /**
  24594. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  24595. */
  24596. VertexBuffer.prototype.dispose = function () {
  24597. if (this._ownsBuffer) {
  24598. this._buffer.dispose();
  24599. }
  24600. };
  24601. Object.defineProperty(VertexBuffer, "PositionKind", {
  24602. get: function () {
  24603. return VertexBuffer._PositionKind;
  24604. },
  24605. enumerable: true,
  24606. configurable: true
  24607. });
  24608. Object.defineProperty(VertexBuffer, "NormalKind", {
  24609. get: function () {
  24610. return VertexBuffer._NormalKind;
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. Object.defineProperty(VertexBuffer, "TangentKind", {
  24616. get: function () {
  24617. return VertexBuffer._TangentKind;
  24618. },
  24619. enumerable: true,
  24620. configurable: true
  24621. });
  24622. Object.defineProperty(VertexBuffer, "UVKind", {
  24623. get: function () {
  24624. return VertexBuffer._UVKind;
  24625. },
  24626. enumerable: true,
  24627. configurable: true
  24628. });
  24629. Object.defineProperty(VertexBuffer, "UV2Kind", {
  24630. get: function () {
  24631. return VertexBuffer._UV2Kind;
  24632. },
  24633. enumerable: true,
  24634. configurable: true
  24635. });
  24636. Object.defineProperty(VertexBuffer, "UV3Kind", {
  24637. get: function () {
  24638. return VertexBuffer._UV3Kind;
  24639. },
  24640. enumerable: true,
  24641. configurable: true
  24642. });
  24643. Object.defineProperty(VertexBuffer, "UV4Kind", {
  24644. get: function () {
  24645. return VertexBuffer._UV4Kind;
  24646. },
  24647. enumerable: true,
  24648. configurable: true
  24649. });
  24650. Object.defineProperty(VertexBuffer, "UV5Kind", {
  24651. get: function () {
  24652. return VertexBuffer._UV5Kind;
  24653. },
  24654. enumerable: true,
  24655. configurable: true
  24656. });
  24657. Object.defineProperty(VertexBuffer, "UV6Kind", {
  24658. get: function () {
  24659. return VertexBuffer._UV6Kind;
  24660. },
  24661. enumerable: true,
  24662. configurable: true
  24663. });
  24664. Object.defineProperty(VertexBuffer, "ColorKind", {
  24665. get: function () {
  24666. return VertexBuffer._ColorKind;
  24667. },
  24668. enumerable: true,
  24669. configurable: true
  24670. });
  24671. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  24672. get: function () {
  24673. return VertexBuffer._MatricesIndicesKind;
  24674. },
  24675. enumerable: true,
  24676. configurable: true
  24677. });
  24678. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  24679. get: function () {
  24680. return VertexBuffer._MatricesWeightsKind;
  24681. },
  24682. enumerable: true,
  24683. configurable: true
  24684. });
  24685. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  24686. get: function () {
  24687. return VertexBuffer._MatricesIndicesExtraKind;
  24688. },
  24689. enumerable: true,
  24690. configurable: true
  24691. });
  24692. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  24693. get: function () {
  24694. return VertexBuffer._MatricesWeightsExtraKind;
  24695. },
  24696. enumerable: true,
  24697. configurable: true
  24698. });
  24699. // Enums
  24700. VertexBuffer._PositionKind = "position";
  24701. VertexBuffer._NormalKind = "normal";
  24702. VertexBuffer._TangentKind = "tangent";
  24703. VertexBuffer._UVKind = "uv";
  24704. VertexBuffer._UV2Kind = "uv2";
  24705. VertexBuffer._UV3Kind = "uv3";
  24706. VertexBuffer._UV4Kind = "uv4";
  24707. VertexBuffer._UV5Kind = "uv5";
  24708. VertexBuffer._UV6Kind = "uv6";
  24709. VertexBuffer._ColorKind = "color";
  24710. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  24711. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  24712. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  24713. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  24714. return VertexBuffer;
  24715. }());
  24716. BABYLON.VertexBuffer = VertexBuffer;
  24717. })(BABYLON || (BABYLON = {}));
  24718. //# sourceMappingURL=babylon.vertexBuffer.js.map
  24719. var BABYLON;
  24720. (function (BABYLON) {
  24721. /**
  24722. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  24723. */
  24724. var DummyInternalTextureTracker = /** @class */ (function () {
  24725. function DummyInternalTextureTracker() {
  24726. /**
  24727. * Gets or set the previous tracker in the list
  24728. */
  24729. this.previous = null;
  24730. /**
  24731. * Gets or set the next tracker in the list
  24732. */
  24733. this.next = null;
  24734. }
  24735. return DummyInternalTextureTracker;
  24736. }());
  24737. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  24738. })(BABYLON || (BABYLON = {}));
  24739. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  24740. var BABYLON;
  24741. (function (BABYLON) {
  24742. /**
  24743. * Class used to store data associated with WebGL texture data for the engine
  24744. * This class should not be used directly
  24745. */
  24746. var InternalTexture = /** @class */ (function () {
  24747. /**
  24748. * Creates a new InternalTexture
  24749. * @param engine defines the engine to use
  24750. * @param dataSource defines the type of data that will be used
  24751. */
  24752. function InternalTexture(engine, dataSource) {
  24753. /**
  24754. * Observable called when the texture is loaded
  24755. */
  24756. this.onLoadedObservable = new BABYLON.Observable();
  24757. /**
  24758. * Gets or set the previous tracker in the list
  24759. */
  24760. this.previous = null;
  24761. /**
  24762. * Gets or set the next tracker in the list
  24763. */
  24764. this.next = null;
  24765. // Private
  24766. /** @ignore */
  24767. this._initialSlot = -1;
  24768. /** @ignore */
  24769. this._designatedSlot = -1;
  24770. /** @ignore */
  24771. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24772. /** @ignore */
  24773. this._references = 1;
  24774. this._engine = engine;
  24775. this._dataSource = dataSource;
  24776. this._webGLTexture = engine._createTexture();
  24777. }
  24778. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24779. /**
  24780. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24781. */
  24782. get: function () {
  24783. return this._dataSource;
  24784. },
  24785. enumerable: true,
  24786. configurable: true
  24787. });
  24788. /**
  24789. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24790. */
  24791. InternalTexture.prototype.incrementReferences = function () {
  24792. this._references++;
  24793. };
  24794. /**
  24795. * Change the size of the texture (not the size of the content)
  24796. * @param width defines the new width
  24797. * @param height defines the new height
  24798. * @param depth defines the new depth (1 by default)
  24799. */
  24800. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24801. if (depth === void 0) { depth = 1; }
  24802. this.width = width;
  24803. this.height = height;
  24804. this.depth = depth;
  24805. this.baseWidth = width;
  24806. this.baseHeight = height;
  24807. this.baseDepth = depth;
  24808. this._size = width * height * depth;
  24809. };
  24810. /** @ignore */
  24811. InternalTexture.prototype._rebuild = function () {
  24812. var _this = this;
  24813. var proxy;
  24814. this.isReady = false;
  24815. this._cachedCoordinatesMode = null;
  24816. this._cachedWrapU = null;
  24817. this._cachedWrapV = null;
  24818. this._cachedAnisotropicFilteringLevel = null;
  24819. switch (this._dataSource) {
  24820. case InternalTexture.DATASOURCE_TEMP:
  24821. return;
  24822. case InternalTexture.DATASOURCE_URL:
  24823. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24824. _this.isReady = true;
  24825. }, null, this._buffer, undefined, this.format);
  24826. proxy._swapAndDie(this);
  24827. return;
  24828. case InternalTexture.DATASOURCE_RAW:
  24829. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24830. proxy._swapAndDie(this);
  24831. this.isReady = true;
  24832. return;
  24833. case InternalTexture.DATASOURCE_RAW3D:
  24834. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24835. proxy._swapAndDie(this);
  24836. this.isReady = true;
  24837. return;
  24838. case InternalTexture.DATASOURCE_DYNAMIC:
  24839. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24840. proxy._swapAndDie(this);
  24841. // The engine will make sure to update content so no need to flag it as isReady = true
  24842. return;
  24843. case InternalTexture.DATASOURCE_RENDERTARGET:
  24844. var options = new BABYLON.RenderTargetCreationOptions();
  24845. options.generateDepthBuffer = this._generateDepthBuffer;
  24846. options.generateMipMaps = this.generateMipMaps;
  24847. options.generateStencilBuffer = this._generateStencilBuffer;
  24848. options.samplingMode = this.samplingMode;
  24849. options.type = this.type;
  24850. if (this.isCube) {
  24851. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24852. }
  24853. else {
  24854. var size = {
  24855. width: this.width,
  24856. height: this.height
  24857. };
  24858. proxy = this._engine.createRenderTargetTexture(size, options);
  24859. }
  24860. proxy._swapAndDie(this);
  24861. this.isReady = true;
  24862. return;
  24863. case InternalTexture.DATASOURCE_CUBE:
  24864. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24865. _this.isReady = true;
  24866. }, null, this.format, this._extension);
  24867. proxy._swapAndDie(this);
  24868. return;
  24869. case InternalTexture.DATASOURCE_CUBERAW:
  24870. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24871. proxy._swapAndDie(this);
  24872. this.isReady = true;
  24873. return;
  24874. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24875. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24876. if (proxy) {
  24877. proxy._swapAndDie(_this);
  24878. }
  24879. _this.isReady = true;
  24880. }, null, this.format, this._extension);
  24881. return;
  24882. }
  24883. };
  24884. InternalTexture.prototype._swapAndDie = function (target) {
  24885. target._webGLTexture = this._webGLTexture;
  24886. if (this._framebuffer) {
  24887. target._framebuffer = this._framebuffer;
  24888. }
  24889. if (this._depthStencilBuffer) {
  24890. target._depthStencilBuffer = this._depthStencilBuffer;
  24891. }
  24892. if (this._lodTextureHigh) {
  24893. if (target._lodTextureHigh) {
  24894. target._lodTextureHigh.dispose();
  24895. }
  24896. target._lodTextureHigh = this._lodTextureHigh;
  24897. }
  24898. if (this._lodTextureMid) {
  24899. if (target._lodTextureMid) {
  24900. target._lodTextureMid.dispose();
  24901. }
  24902. target._lodTextureMid = this._lodTextureMid;
  24903. }
  24904. if (this._lodTextureLow) {
  24905. if (target._lodTextureLow) {
  24906. target._lodTextureLow.dispose();
  24907. }
  24908. target._lodTextureLow = this._lodTextureLow;
  24909. }
  24910. var cache = this._engine.getLoadedTexturesCache();
  24911. var index = cache.indexOf(this);
  24912. if (index !== -1) {
  24913. cache.splice(index, 1);
  24914. }
  24915. };
  24916. /**
  24917. * Dispose the current allocated resources
  24918. */
  24919. InternalTexture.prototype.dispose = function () {
  24920. if (!this._webGLTexture) {
  24921. return;
  24922. }
  24923. this._references--;
  24924. if (this._references === 0) {
  24925. this._engine._releaseTexture(this);
  24926. this._webGLTexture = null;
  24927. this.previous = null;
  24928. this.next = null;
  24929. }
  24930. };
  24931. /**
  24932. * The source of the texture data is unknown
  24933. */
  24934. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24935. /**
  24936. * Texture data comes from an URL
  24937. */
  24938. InternalTexture.DATASOURCE_URL = 1;
  24939. /**
  24940. * Texture data is only used for temporary storage
  24941. */
  24942. InternalTexture.DATASOURCE_TEMP = 2;
  24943. /**
  24944. * Texture data comes from raw data (ArrayBuffer)
  24945. */
  24946. InternalTexture.DATASOURCE_RAW = 3;
  24947. /**
  24948. * Texture content is dynamic (video or dynamic texture)
  24949. */
  24950. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24951. /**
  24952. * Texture content is generated by rendering to it
  24953. */
  24954. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24955. /**
  24956. * Texture content is part of a multi render target process
  24957. */
  24958. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24959. /**
  24960. * Texture data comes from a cube data file
  24961. */
  24962. InternalTexture.DATASOURCE_CUBE = 7;
  24963. /**
  24964. * Texture data comes from a raw cube data
  24965. */
  24966. InternalTexture.DATASOURCE_CUBERAW = 8;
  24967. /**
  24968. * Texture data come from a prefiltered cube data file
  24969. */
  24970. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24971. /**
  24972. * Texture content is raw 3D data
  24973. */
  24974. InternalTexture.DATASOURCE_RAW3D = 10;
  24975. return InternalTexture;
  24976. }());
  24977. BABYLON.InternalTexture = InternalTexture;
  24978. })(BABYLON || (BABYLON = {}));
  24979. //# sourceMappingURL=babylon.internalTexture.js.map
  24980. var BABYLON;
  24981. (function (BABYLON) {
  24982. var BaseTexture = /** @class */ (function () {
  24983. function BaseTexture(scene) {
  24984. this._hasAlpha = false;
  24985. this.getAlphaFromRGB = false;
  24986. this.level = 1;
  24987. this.coordinatesIndex = 0;
  24988. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24989. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24990. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24991. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24992. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24993. this.isCube = false;
  24994. this.is3D = false;
  24995. this.gammaSpace = true;
  24996. this.invertZ = false;
  24997. this.lodLevelInAlpha = false;
  24998. this.lodGenerationOffset = 0.0;
  24999. this.lodGenerationScale = 0.8;
  25000. this.isRenderTarget = false;
  25001. this.animations = new Array();
  25002. /**
  25003. * An event triggered when the texture is disposed.
  25004. * @type {BABYLON.Observable}
  25005. */
  25006. this.onDisposeObservable = new BABYLON.Observable();
  25007. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25008. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25009. if (this._scene) {
  25010. this._scene.textures.push(this);
  25011. }
  25012. this._uid = null;
  25013. }
  25014. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25015. get: function () {
  25016. return this._hasAlpha;
  25017. },
  25018. set: function (value) {
  25019. if (this._hasAlpha === value) {
  25020. return;
  25021. }
  25022. this._hasAlpha = value;
  25023. if (this._scene) {
  25024. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25025. }
  25026. },
  25027. enumerable: true,
  25028. configurable: true
  25029. });
  25030. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25031. get: function () {
  25032. return this._coordinatesMode;
  25033. },
  25034. set: function (value) {
  25035. if (this._coordinatesMode === value) {
  25036. return;
  25037. }
  25038. this._coordinatesMode = value;
  25039. if (this._scene) {
  25040. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25041. }
  25042. },
  25043. enumerable: true,
  25044. configurable: true
  25045. });
  25046. Object.defineProperty(BaseTexture.prototype, "uid", {
  25047. get: function () {
  25048. if (!this._uid) {
  25049. this._uid = BABYLON.Tools.RandomId();
  25050. }
  25051. return this._uid;
  25052. },
  25053. enumerable: true,
  25054. configurable: true
  25055. });
  25056. BaseTexture.prototype.toString = function () {
  25057. return this.name;
  25058. };
  25059. BaseTexture.prototype.getClassName = function () {
  25060. return "BaseTexture";
  25061. };
  25062. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  25063. set: function (callback) {
  25064. if (this._onDisposeObserver) {
  25065. this.onDisposeObservable.remove(this._onDisposeObserver);
  25066. }
  25067. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25068. },
  25069. enumerable: true,
  25070. configurable: true
  25071. });
  25072. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  25073. get: function () {
  25074. return true;
  25075. },
  25076. enumerable: true,
  25077. configurable: true
  25078. });
  25079. BaseTexture.prototype.getScene = function () {
  25080. return this._scene;
  25081. };
  25082. BaseTexture.prototype.getTextureMatrix = function () {
  25083. return BABYLON.Matrix.IdentityReadOnly;
  25084. };
  25085. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  25086. return BABYLON.Matrix.IdentityReadOnly;
  25087. };
  25088. BaseTexture.prototype.getInternalTexture = function () {
  25089. return this._texture;
  25090. };
  25091. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  25092. return !this.isBlocking || this.isReady();
  25093. };
  25094. BaseTexture.prototype.isReady = function () {
  25095. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25096. this.delayLoad();
  25097. return false;
  25098. }
  25099. if (this._texture) {
  25100. return this._texture.isReady;
  25101. }
  25102. return false;
  25103. };
  25104. BaseTexture.prototype.getSize = function () {
  25105. if (this._texture && this._texture.width) {
  25106. return new BABYLON.Size(this._texture.width, this._texture.height);
  25107. }
  25108. if (this._texture && this._texture._size) {
  25109. return new BABYLON.Size(this._texture._size, this._texture._size);
  25110. }
  25111. return BABYLON.Size.Zero();
  25112. };
  25113. BaseTexture.prototype.getBaseSize = function () {
  25114. if (!this.isReady() || !this._texture)
  25115. return BABYLON.Size.Zero();
  25116. if (this._texture._size) {
  25117. return new BABYLON.Size(this._texture._size, this._texture._size);
  25118. }
  25119. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25120. };
  25121. BaseTexture.prototype.scale = function (ratio) {
  25122. };
  25123. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25124. get: function () {
  25125. return false;
  25126. },
  25127. enumerable: true,
  25128. configurable: true
  25129. });
  25130. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25131. if (!this._scene) {
  25132. return null;
  25133. }
  25134. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25135. for (var index = 0; index < texturesCache.length; index++) {
  25136. var texturesCacheEntry = texturesCache[index];
  25137. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25138. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25139. texturesCacheEntry.incrementReferences();
  25140. return texturesCacheEntry;
  25141. }
  25142. }
  25143. }
  25144. return null;
  25145. };
  25146. BaseTexture.prototype._rebuild = function () {
  25147. };
  25148. BaseTexture.prototype.delayLoad = function () {
  25149. };
  25150. BaseTexture.prototype.clone = function () {
  25151. return null;
  25152. };
  25153. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25154. get: function () {
  25155. if (!this._texture) {
  25156. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25157. }
  25158. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25159. },
  25160. enumerable: true,
  25161. configurable: true
  25162. });
  25163. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25164. get: function () {
  25165. if (!this._texture) {
  25166. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25167. }
  25168. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25169. },
  25170. enumerable: true,
  25171. configurable: true
  25172. });
  25173. BaseTexture.prototype.readPixels = function (faceIndex) {
  25174. if (faceIndex === void 0) { faceIndex = 0; }
  25175. if (!this._texture) {
  25176. return null;
  25177. }
  25178. var size = this.getSize();
  25179. var scene = this.getScene();
  25180. if (!scene) {
  25181. return null;
  25182. }
  25183. var engine = scene.getEngine();
  25184. if (this._texture.isCube) {
  25185. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  25186. }
  25187. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  25188. };
  25189. BaseTexture.prototype.releaseInternalTexture = function () {
  25190. if (this._texture) {
  25191. this._texture.dispose();
  25192. this._texture = null;
  25193. }
  25194. };
  25195. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  25196. get: function () {
  25197. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  25198. return null;
  25199. }
  25200. if (!this._texture._sphericalPolynomial) {
  25201. this._texture._sphericalPolynomial =
  25202. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  25203. }
  25204. return this._texture._sphericalPolynomial;
  25205. },
  25206. set: function (value) {
  25207. if (this._texture) {
  25208. this._texture._sphericalPolynomial = value;
  25209. }
  25210. },
  25211. enumerable: true,
  25212. configurable: true
  25213. });
  25214. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  25215. get: function () {
  25216. if (this._texture) {
  25217. return this._texture._lodTextureHigh;
  25218. }
  25219. return null;
  25220. },
  25221. enumerable: true,
  25222. configurable: true
  25223. });
  25224. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  25225. get: function () {
  25226. if (this._texture) {
  25227. return this._texture._lodTextureMid;
  25228. }
  25229. return null;
  25230. },
  25231. enumerable: true,
  25232. configurable: true
  25233. });
  25234. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  25235. get: function () {
  25236. if (this._texture) {
  25237. return this._texture._lodTextureLow;
  25238. }
  25239. return null;
  25240. },
  25241. enumerable: true,
  25242. configurable: true
  25243. });
  25244. BaseTexture.prototype.dispose = function () {
  25245. if (!this._scene) {
  25246. return;
  25247. }
  25248. // Animations
  25249. this._scene.stopAnimation(this);
  25250. // Remove from scene
  25251. this._scene._removePendingData(this);
  25252. var index = this._scene.textures.indexOf(this);
  25253. if (index >= 0) {
  25254. this._scene.textures.splice(index, 1);
  25255. }
  25256. if (this._texture === undefined) {
  25257. return;
  25258. }
  25259. // Release
  25260. this.releaseInternalTexture();
  25261. // Callback
  25262. this.onDisposeObservable.notifyObservers(this);
  25263. this.onDisposeObservable.clear();
  25264. };
  25265. BaseTexture.prototype.serialize = function () {
  25266. if (!this.name) {
  25267. return null;
  25268. }
  25269. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25270. // Animations
  25271. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25272. return serializationObject;
  25273. };
  25274. BaseTexture.WhenAllReady = function (textures, callback) {
  25275. var numRemaining = textures.length;
  25276. if (numRemaining === 0) {
  25277. callback();
  25278. return;
  25279. }
  25280. var _loop_1 = function () {
  25281. texture = textures[i];
  25282. if (texture.isReady()) {
  25283. if (--numRemaining === 0) {
  25284. callback();
  25285. }
  25286. }
  25287. else {
  25288. onLoadObservable = texture.onLoadObservable;
  25289. var onLoadCallback_1 = function () {
  25290. onLoadObservable.removeCallback(onLoadCallback_1);
  25291. if (--numRemaining === 0) {
  25292. callback();
  25293. }
  25294. };
  25295. onLoadObservable.add(onLoadCallback_1);
  25296. }
  25297. };
  25298. var texture, onLoadObservable;
  25299. for (var i = 0; i < textures.length; i++) {
  25300. _loop_1();
  25301. }
  25302. };
  25303. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  25304. __decorate([
  25305. BABYLON.serialize()
  25306. ], BaseTexture.prototype, "name", void 0);
  25307. __decorate([
  25308. BABYLON.serialize("hasAlpha")
  25309. ], BaseTexture.prototype, "_hasAlpha", void 0);
  25310. __decorate([
  25311. BABYLON.serialize()
  25312. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  25313. __decorate([
  25314. BABYLON.serialize()
  25315. ], BaseTexture.prototype, "level", void 0);
  25316. __decorate([
  25317. BABYLON.serialize()
  25318. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  25319. __decorate([
  25320. BABYLON.serialize("coordinatesMode")
  25321. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  25322. __decorate([
  25323. BABYLON.serialize()
  25324. ], BaseTexture.prototype, "wrapU", void 0);
  25325. __decorate([
  25326. BABYLON.serialize()
  25327. ], BaseTexture.prototype, "wrapV", void 0);
  25328. __decorate([
  25329. BABYLON.serialize()
  25330. ], BaseTexture.prototype, "wrapR", void 0);
  25331. __decorate([
  25332. BABYLON.serialize()
  25333. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  25334. __decorate([
  25335. BABYLON.serialize()
  25336. ], BaseTexture.prototype, "isCube", void 0);
  25337. __decorate([
  25338. BABYLON.serialize()
  25339. ], BaseTexture.prototype, "is3D", void 0);
  25340. __decorate([
  25341. BABYLON.serialize()
  25342. ], BaseTexture.prototype, "gammaSpace", void 0);
  25343. __decorate([
  25344. BABYLON.serialize()
  25345. ], BaseTexture.prototype, "invertZ", void 0);
  25346. __decorate([
  25347. BABYLON.serialize()
  25348. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  25349. __decorate([
  25350. BABYLON.serialize()
  25351. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  25352. __decorate([
  25353. BABYLON.serialize()
  25354. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  25355. __decorate([
  25356. BABYLON.serialize()
  25357. ], BaseTexture.prototype, "isRenderTarget", void 0);
  25358. return BaseTexture;
  25359. }());
  25360. BABYLON.BaseTexture = BaseTexture;
  25361. })(BABYLON || (BABYLON = {}));
  25362. //# sourceMappingURL=babylon.baseTexture.js.map
  25363. var BABYLON;
  25364. (function (BABYLON) {
  25365. var Texture = /** @class */ (function (_super) {
  25366. __extends(Texture, _super);
  25367. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  25368. if (noMipmap === void 0) { noMipmap = false; }
  25369. if (invertY === void 0) { invertY = true; }
  25370. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25371. if (onLoad === void 0) { onLoad = null; }
  25372. if (onError === void 0) { onError = null; }
  25373. if (buffer === void 0) { buffer = null; }
  25374. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25375. var _this = _super.call(this, scene) || this;
  25376. _this.uOffset = 0;
  25377. _this.vOffset = 0;
  25378. _this.uScale = 1.0;
  25379. _this.vScale = 1.0;
  25380. _this.uAng = 0;
  25381. _this.vAng = 0;
  25382. _this.wAng = 0;
  25383. _this._isBlocking = true;
  25384. _this.name = url || "";
  25385. _this.url = url;
  25386. _this._noMipmap = noMipmap;
  25387. _this._invertY = invertY;
  25388. _this._samplingMode = samplingMode;
  25389. _this._buffer = buffer;
  25390. _this._deleteBuffer = deleteBuffer;
  25391. if (format) {
  25392. _this._format = format;
  25393. }
  25394. scene = _this.getScene();
  25395. if (!scene) {
  25396. return _this;
  25397. }
  25398. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  25399. var load = function () {
  25400. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  25401. _this.onLoadObservable.notifyObservers(_this);
  25402. }
  25403. if (onLoad) {
  25404. onLoad();
  25405. }
  25406. if (!_this.isBlocking && scene) {
  25407. scene.resetCachedMaterial();
  25408. }
  25409. };
  25410. if (!_this.url) {
  25411. _this._delayedOnLoad = load;
  25412. _this._delayedOnError = onError;
  25413. return _this;
  25414. }
  25415. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  25416. if (!_this._texture) {
  25417. if (!scene.useDelayedTextureLoading) {
  25418. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  25419. if (deleteBuffer) {
  25420. delete _this._buffer;
  25421. }
  25422. }
  25423. else {
  25424. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25425. _this._delayedOnLoad = load;
  25426. _this._delayedOnError = onError;
  25427. }
  25428. }
  25429. else {
  25430. if (_this._texture.isReady) {
  25431. BABYLON.Tools.SetImmediate(function () { return load(); });
  25432. }
  25433. else {
  25434. _this._texture.onLoadedObservable.add(load);
  25435. }
  25436. }
  25437. return _this;
  25438. }
  25439. Object.defineProperty(Texture.prototype, "noMipmap", {
  25440. get: function () {
  25441. return this._noMipmap;
  25442. },
  25443. enumerable: true,
  25444. configurable: true
  25445. });
  25446. Object.defineProperty(Texture.prototype, "isBlocking", {
  25447. get: function () {
  25448. return this._isBlocking;
  25449. },
  25450. set: function (value) {
  25451. this._isBlocking = value;
  25452. },
  25453. enumerable: true,
  25454. configurable: true
  25455. });
  25456. Object.defineProperty(Texture.prototype, "samplingMode", {
  25457. get: function () {
  25458. return this._samplingMode;
  25459. },
  25460. enumerable: true,
  25461. configurable: true
  25462. });
  25463. Texture.prototype.updateURL = function (url) {
  25464. this.url = url;
  25465. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25466. this.delayLoad();
  25467. };
  25468. Texture.prototype.delayLoad = function () {
  25469. var _this = this;
  25470. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25471. return;
  25472. }
  25473. var scene = this.getScene();
  25474. if (!scene) {
  25475. return;
  25476. }
  25477. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25478. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  25479. if (!this._texture) {
  25480. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  25481. if (this._deleteBuffer) {
  25482. delete this._buffer;
  25483. }
  25484. }
  25485. else {
  25486. if (this._texture.isReady) {
  25487. BABYLON.Tools.SetImmediate(function () {
  25488. if (!_this._delayedOnLoad) {
  25489. return;
  25490. }
  25491. _this._delayedOnLoad();
  25492. });
  25493. }
  25494. else {
  25495. if (this._delayedOnLoad) {
  25496. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  25497. }
  25498. }
  25499. }
  25500. };
  25501. Texture.prototype.updateSamplingMode = function (samplingMode) {
  25502. if (!this._texture) {
  25503. return;
  25504. }
  25505. var scene = this.getScene();
  25506. if (!scene) {
  25507. return;
  25508. }
  25509. this._samplingMode = samplingMode;
  25510. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  25511. };
  25512. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  25513. x *= this.uScale;
  25514. y *= this.vScale;
  25515. x -= 0.5 * this.uScale;
  25516. y -= 0.5 * this.vScale;
  25517. z -= 0.5;
  25518. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  25519. t.x += 0.5 * this.uScale + this.uOffset;
  25520. t.y += 0.5 * this.vScale + this.vOffset;
  25521. t.z += 0.5;
  25522. };
  25523. Texture.prototype.getTextureMatrix = function () {
  25524. var _this = this;
  25525. if (this.uOffset === this._cachedUOffset &&
  25526. this.vOffset === this._cachedVOffset &&
  25527. this.uScale === this._cachedUScale &&
  25528. this.vScale === this._cachedVScale &&
  25529. this.uAng === this._cachedUAng &&
  25530. this.vAng === this._cachedVAng &&
  25531. this.wAng === this._cachedWAng) {
  25532. return this._cachedTextureMatrix;
  25533. }
  25534. this._cachedUOffset = this.uOffset;
  25535. this._cachedVOffset = this.vOffset;
  25536. this._cachedUScale = this.uScale;
  25537. this._cachedVScale = this.vScale;
  25538. this._cachedUAng = this.uAng;
  25539. this._cachedVAng = this.vAng;
  25540. this._cachedWAng = this.wAng;
  25541. if (!this._cachedTextureMatrix) {
  25542. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25543. this._rowGenerationMatrix = new BABYLON.Matrix();
  25544. this._t0 = BABYLON.Vector3.Zero();
  25545. this._t1 = BABYLON.Vector3.Zero();
  25546. this._t2 = BABYLON.Vector3.Zero();
  25547. }
  25548. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  25549. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  25550. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  25551. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  25552. this._t1.subtractInPlace(this._t0);
  25553. this._t2.subtractInPlace(this._t0);
  25554. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25555. this._cachedTextureMatrix.m[0] = this._t1.x;
  25556. this._cachedTextureMatrix.m[1] = this._t1.y;
  25557. this._cachedTextureMatrix.m[2] = this._t1.z;
  25558. this._cachedTextureMatrix.m[4] = this._t2.x;
  25559. this._cachedTextureMatrix.m[5] = this._t2.y;
  25560. this._cachedTextureMatrix.m[6] = this._t2.z;
  25561. this._cachedTextureMatrix.m[8] = this._t0.x;
  25562. this._cachedTextureMatrix.m[9] = this._t0.y;
  25563. this._cachedTextureMatrix.m[10] = this._t0.z;
  25564. var scene = this.getScene();
  25565. if (!scene) {
  25566. return this._cachedTextureMatrix;
  25567. }
  25568. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25569. return mat.hasTexture(_this);
  25570. });
  25571. return this._cachedTextureMatrix;
  25572. };
  25573. Texture.prototype.getReflectionTextureMatrix = function () {
  25574. var _this = this;
  25575. var scene = this.getScene();
  25576. if (!scene) {
  25577. return this._cachedTextureMatrix;
  25578. }
  25579. if (this.uOffset === this._cachedUOffset &&
  25580. this.vOffset === this._cachedVOffset &&
  25581. this.uScale === this._cachedUScale &&
  25582. this.vScale === this._cachedVScale &&
  25583. this.coordinatesMode === this._cachedCoordinatesMode) {
  25584. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  25585. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  25586. return this._cachedTextureMatrix;
  25587. }
  25588. }
  25589. else {
  25590. return this._cachedTextureMatrix;
  25591. }
  25592. }
  25593. if (!this._cachedTextureMatrix) {
  25594. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25595. }
  25596. if (!this._projectionModeMatrix) {
  25597. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  25598. }
  25599. this._cachedUOffset = this.uOffset;
  25600. this._cachedVOffset = this.vOffset;
  25601. this._cachedUScale = this.uScale;
  25602. this._cachedVScale = this.vScale;
  25603. this._cachedCoordinatesMode = this.coordinatesMode;
  25604. switch (this.coordinatesMode) {
  25605. case Texture.PLANAR_MODE:
  25606. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25607. this._cachedTextureMatrix[0] = this.uScale;
  25608. this._cachedTextureMatrix[5] = this.vScale;
  25609. this._cachedTextureMatrix[12] = this.uOffset;
  25610. this._cachedTextureMatrix[13] = this.vOffset;
  25611. break;
  25612. case Texture.PROJECTION_MODE:
  25613. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  25614. this._projectionModeMatrix.m[0] = 0.5;
  25615. this._projectionModeMatrix.m[5] = -0.5;
  25616. this._projectionModeMatrix.m[10] = 0.0;
  25617. this._projectionModeMatrix.m[12] = 0.5;
  25618. this._projectionModeMatrix.m[13] = 0.5;
  25619. this._projectionModeMatrix.m[14] = 1.0;
  25620. this._projectionModeMatrix.m[15] = 1.0;
  25621. var projectionMatrix = scene.getProjectionMatrix();
  25622. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  25623. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  25624. break;
  25625. default:
  25626. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25627. break;
  25628. }
  25629. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25630. return (mat.getActiveTextures().indexOf(_this) !== -1);
  25631. });
  25632. return this._cachedTextureMatrix;
  25633. };
  25634. Texture.prototype.clone = function () {
  25635. var _this = this;
  25636. return BABYLON.SerializationHelper.Clone(function () {
  25637. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  25638. }, this);
  25639. };
  25640. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  25641. get: function () {
  25642. if (!this._onLoadObservable) {
  25643. this._onLoadObservable = new BABYLON.Observable();
  25644. }
  25645. return this._onLoadObservable;
  25646. },
  25647. enumerable: true,
  25648. configurable: true
  25649. });
  25650. Texture.prototype.serialize = function () {
  25651. var serializationObject = _super.prototype.serialize.call(this);
  25652. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  25653. serializationObject.base64String = this._buffer;
  25654. serializationObject.name = serializationObject.name.replace("data:", "");
  25655. }
  25656. return serializationObject;
  25657. };
  25658. Texture.prototype.getClassName = function () {
  25659. return "Texture";
  25660. };
  25661. Texture.prototype.dispose = function () {
  25662. _super.prototype.dispose.call(this);
  25663. if (this.onLoadObservable) {
  25664. this.onLoadObservable.clear();
  25665. this._onLoadObservable = null;
  25666. }
  25667. this._delayedOnLoad = null;
  25668. this._delayedOnError = null;
  25669. };
  25670. // Statics
  25671. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25672. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25673. if (onLoad === void 0) { onLoad = null; }
  25674. if (onError === void 0) { onError = null; }
  25675. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25676. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  25677. };
  25678. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  25679. if (parsedTexture.customType) {
  25680. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  25681. // Update Sampling Mode
  25682. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  25683. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  25684. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  25685. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  25686. }
  25687. }
  25688. return parsedCustomTexture;
  25689. }
  25690. if (parsedTexture.isCube) {
  25691. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  25692. }
  25693. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  25694. return null;
  25695. }
  25696. var texture = BABYLON.SerializationHelper.Parse(function () {
  25697. var generateMipMaps = true;
  25698. if (parsedTexture.noMipmap) {
  25699. generateMipMaps = false;
  25700. }
  25701. if (parsedTexture.mirrorPlane) {
  25702. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25703. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  25704. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  25705. return mirrorTexture;
  25706. }
  25707. else if (parsedTexture.isRenderTarget) {
  25708. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25709. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  25710. return renderTargetTexture;
  25711. }
  25712. else {
  25713. var texture;
  25714. if (parsedTexture.base64String) {
  25715. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  25716. }
  25717. else {
  25718. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  25719. }
  25720. return texture;
  25721. }
  25722. }, parsedTexture, scene);
  25723. // Update Sampling Mode
  25724. if (parsedTexture.samplingMode) {
  25725. var sampling = parsedTexture.samplingMode;
  25726. if (texture._samplingMode !== sampling) {
  25727. texture.updateSamplingMode(sampling);
  25728. }
  25729. }
  25730. // Animations
  25731. if (parsedTexture.animations) {
  25732. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  25733. var parsedAnimation = parsedTexture.animations[animationIndex];
  25734. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25735. }
  25736. }
  25737. return texture;
  25738. };
  25739. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25740. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25741. if (noMipmap === void 0) { noMipmap = false; }
  25742. if (invertY === void 0) { invertY = true; }
  25743. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25744. if (onLoad === void 0) { onLoad = null; }
  25745. if (onError === void 0) { onError = null; }
  25746. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25747. if (name.substr(0, 5) !== "data:") {
  25748. name = "data:" + name;
  25749. }
  25750. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  25751. };
  25752. // Constants
  25753. Texture.NEAREST_SAMPLINGMODE = 1;
  25754. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25755. Texture.BILINEAR_SAMPLINGMODE = 2;
  25756. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25757. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25758. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25759. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25760. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25761. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25762. Texture.NEAREST_LINEAR = 7;
  25763. Texture.NEAREST_NEAREST = 8;
  25764. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25765. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25766. Texture.LINEAR_LINEAR = 11;
  25767. Texture.LINEAR_NEAREST = 12;
  25768. Texture.EXPLICIT_MODE = 0;
  25769. Texture.SPHERICAL_MODE = 1;
  25770. Texture.PLANAR_MODE = 2;
  25771. Texture.CUBIC_MODE = 3;
  25772. Texture.PROJECTION_MODE = 4;
  25773. Texture.SKYBOX_MODE = 5;
  25774. Texture.INVCUBIC_MODE = 6;
  25775. Texture.EQUIRECTANGULAR_MODE = 7;
  25776. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25777. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25778. Texture.CLAMP_ADDRESSMODE = 0;
  25779. Texture.WRAP_ADDRESSMODE = 1;
  25780. Texture.MIRROR_ADDRESSMODE = 2;
  25781. __decorate([
  25782. BABYLON.serialize()
  25783. ], Texture.prototype, "url", void 0);
  25784. __decorate([
  25785. BABYLON.serialize()
  25786. ], Texture.prototype, "uOffset", void 0);
  25787. __decorate([
  25788. BABYLON.serialize()
  25789. ], Texture.prototype, "vOffset", void 0);
  25790. __decorate([
  25791. BABYLON.serialize()
  25792. ], Texture.prototype, "uScale", void 0);
  25793. __decorate([
  25794. BABYLON.serialize()
  25795. ], Texture.prototype, "vScale", void 0);
  25796. __decorate([
  25797. BABYLON.serialize()
  25798. ], Texture.prototype, "uAng", void 0);
  25799. __decorate([
  25800. BABYLON.serialize()
  25801. ], Texture.prototype, "vAng", void 0);
  25802. __decorate([
  25803. BABYLON.serialize()
  25804. ], Texture.prototype, "wAng", void 0);
  25805. __decorate([
  25806. BABYLON.serialize()
  25807. ], Texture.prototype, "isBlocking", null);
  25808. return Texture;
  25809. }(BABYLON.BaseTexture));
  25810. BABYLON.Texture = Texture;
  25811. })(BABYLON || (BABYLON = {}));
  25812. //# sourceMappingURL=babylon.texture.js.map
  25813. var BABYLON;
  25814. (function (BABYLON) {
  25815. var _InstancesBatch = /** @class */ (function () {
  25816. function _InstancesBatch() {
  25817. this.mustReturn = false;
  25818. this.visibleInstances = new Array();
  25819. this.renderSelf = new Array();
  25820. }
  25821. return _InstancesBatch;
  25822. }());
  25823. BABYLON._InstancesBatch = _InstancesBatch;
  25824. var Mesh = /** @class */ (function (_super) {
  25825. __extends(Mesh, _super);
  25826. /**
  25827. * @constructor
  25828. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25829. * @param {Scene} scene The scene to add this mesh to.
  25830. * @param {Node} parent The parent of this mesh, if it has one
  25831. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25832. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25833. * When false, achieved by calling a clone(), also passing False.
  25834. * This will make creation of children, recursive.
  25835. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25836. */
  25837. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25838. if (scene === void 0) { scene = null; }
  25839. if (parent === void 0) { parent = null; }
  25840. if (source === void 0) { source = null; }
  25841. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25842. var _this = _super.call(this, name, scene) || this;
  25843. // Events
  25844. /**
  25845. * An event triggered before rendering the mesh
  25846. * @type {BABYLON.Observable}
  25847. */
  25848. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25849. /**
  25850. * An event triggered after rendering the mesh
  25851. * @type {BABYLON.Observable}
  25852. */
  25853. _this.onAfterRenderObservable = new BABYLON.Observable();
  25854. /**
  25855. * An event triggered before drawing the mesh
  25856. * @type {BABYLON.Observable}
  25857. */
  25858. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25859. // Members
  25860. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25861. _this.instances = new Array();
  25862. _this._LODLevels = new Array();
  25863. _this._visibleInstances = {};
  25864. _this._renderIdForInstances = new Array();
  25865. _this._batchCache = new _InstancesBatch();
  25866. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25867. // Use by builder only to know what orientation were the mesh build in.
  25868. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25869. _this.overrideMaterialSideOrientation = null;
  25870. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25871. // Will be used to save a source mesh reference, If any
  25872. _this._source = null;
  25873. scene = _this.getScene();
  25874. if (source) {
  25875. // Source mesh
  25876. _this._source = source;
  25877. // Geometry
  25878. if (source._geometry) {
  25879. source._geometry.applyToMesh(_this);
  25880. }
  25881. // Deep copy
  25882. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25883. // Metadata
  25884. if (source.metadata && source.metadata.clone) {
  25885. _this.metadata = source.metadata.clone();
  25886. }
  25887. else {
  25888. _this.metadata = source.metadata;
  25889. }
  25890. // Tags
  25891. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25892. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25893. }
  25894. // Parent
  25895. _this.parent = source.parent;
  25896. // Pivot
  25897. _this.setPivotMatrix(source.getPivotMatrix());
  25898. _this.id = name + "." + source.id;
  25899. // Material
  25900. _this.material = source.material;
  25901. var index;
  25902. if (!doNotCloneChildren) {
  25903. // Children
  25904. var directDescendants = source.getDescendants(true);
  25905. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25906. var child = directDescendants[index_1];
  25907. if (child.clone) {
  25908. child.clone(name + "." + child.name, _this);
  25909. }
  25910. }
  25911. }
  25912. // Physics clone
  25913. var physicsEngine = _this.getScene().getPhysicsEngine();
  25914. if (clonePhysicsImpostor && physicsEngine) {
  25915. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25916. if (impostor) {
  25917. _this.physicsImpostor = impostor.clone(_this);
  25918. }
  25919. }
  25920. // Particles
  25921. for (index = 0; index < scene.particleSystems.length; index++) {
  25922. var system = scene.particleSystems[index];
  25923. if (system.emitter === source) {
  25924. system.clone(system.name, _this);
  25925. }
  25926. }
  25927. _this.computeWorldMatrix(true);
  25928. }
  25929. // Parent
  25930. if (parent !== null) {
  25931. _this.parent = parent;
  25932. }
  25933. return _this;
  25934. }
  25935. Object.defineProperty(Mesh, "FRONTSIDE", {
  25936. /**
  25937. * Mesh side orientation : usually the external or front surface
  25938. */
  25939. get: function () {
  25940. return Mesh._FRONTSIDE;
  25941. },
  25942. enumerable: true,
  25943. configurable: true
  25944. });
  25945. Object.defineProperty(Mesh, "BACKSIDE", {
  25946. /**
  25947. * Mesh side orientation : usually the internal or back surface
  25948. */
  25949. get: function () {
  25950. return Mesh._BACKSIDE;
  25951. },
  25952. enumerable: true,
  25953. configurable: true
  25954. });
  25955. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25956. /**
  25957. * Mesh side orientation : both internal and external or front and back surfaces
  25958. */
  25959. get: function () {
  25960. return Mesh._DOUBLESIDE;
  25961. },
  25962. enumerable: true,
  25963. configurable: true
  25964. });
  25965. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25966. /**
  25967. * Mesh side orientation : by default, `FRONTSIDE`
  25968. */
  25969. get: function () {
  25970. return Mesh._DEFAULTSIDE;
  25971. },
  25972. enumerable: true,
  25973. configurable: true
  25974. });
  25975. Object.defineProperty(Mesh, "NO_CAP", {
  25976. /**
  25977. * Mesh cap setting : no cap
  25978. */
  25979. get: function () {
  25980. return Mesh._NO_CAP;
  25981. },
  25982. enumerable: true,
  25983. configurable: true
  25984. });
  25985. Object.defineProperty(Mesh, "CAP_START", {
  25986. /**
  25987. * Mesh cap setting : one cap at the beginning of the mesh
  25988. */
  25989. get: function () {
  25990. return Mesh._CAP_START;
  25991. },
  25992. enumerable: true,
  25993. configurable: true
  25994. });
  25995. Object.defineProperty(Mesh, "CAP_END", {
  25996. /**
  25997. * Mesh cap setting : one cap at the end of the mesh
  25998. */
  25999. get: function () {
  26000. return Mesh._CAP_END;
  26001. },
  26002. enumerable: true,
  26003. configurable: true
  26004. });
  26005. Object.defineProperty(Mesh, "CAP_ALL", {
  26006. /**
  26007. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26008. */
  26009. get: function () {
  26010. return Mesh._CAP_ALL;
  26011. },
  26012. enumerable: true,
  26013. configurable: true
  26014. });
  26015. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26016. set: function (callback) {
  26017. if (this._onBeforeDrawObserver) {
  26018. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26019. }
  26020. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26021. },
  26022. enumerable: true,
  26023. configurable: true
  26024. });
  26025. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  26026. get: function () {
  26027. return this._morphTargetManager;
  26028. },
  26029. set: function (value) {
  26030. if (this._morphTargetManager === value) {
  26031. return;
  26032. }
  26033. this._morphTargetManager = value;
  26034. this._syncGeometryWithMorphTargetManager();
  26035. },
  26036. enumerable: true,
  26037. configurable: true
  26038. });
  26039. Object.defineProperty(Mesh.prototype, "source", {
  26040. get: function () {
  26041. return this._source;
  26042. },
  26043. enumerable: true,
  26044. configurable: true
  26045. });
  26046. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  26047. get: function () {
  26048. return this._unIndexed;
  26049. },
  26050. set: function (value) {
  26051. if (this._unIndexed !== value) {
  26052. this._unIndexed = value;
  26053. this._markSubMeshesAsAttributesDirty();
  26054. }
  26055. },
  26056. enumerable: true,
  26057. configurable: true
  26058. });
  26059. // Methods
  26060. /**
  26061. * Returns the string "Mesh".
  26062. */
  26063. Mesh.prototype.getClassName = function () {
  26064. return "Mesh";
  26065. };
  26066. /**
  26067. * Returns a string.
  26068. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26069. */
  26070. Mesh.prototype.toString = function (fullDetails) {
  26071. var ret = _super.prototype.toString.call(this, fullDetails);
  26072. ret += ", n vertices: " + this.getTotalVertices();
  26073. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  26074. if (this.animations) {
  26075. for (var i = 0; i < this.animations.length; i++) {
  26076. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  26077. }
  26078. }
  26079. if (fullDetails) {
  26080. if (this._geometry) {
  26081. var ib = this.getIndices();
  26082. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26083. if (vb && ib) {
  26084. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  26085. }
  26086. }
  26087. else {
  26088. ret += ", flat shading: UNKNOWN";
  26089. }
  26090. }
  26091. return ret;
  26092. };
  26093. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  26094. /**
  26095. * True if the mesh has some Levels Of Details (LOD).
  26096. * Returns a boolean.
  26097. */
  26098. get: function () {
  26099. return this._LODLevels.length > 0;
  26100. },
  26101. enumerable: true,
  26102. configurable: true
  26103. });
  26104. /**
  26105. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26106. * @returns an array of {BABYLON.MeshLODLevel}
  26107. */
  26108. Mesh.prototype.getLODLevels = function () {
  26109. return this._LODLevels;
  26110. };
  26111. Mesh.prototype._sortLODLevels = function () {
  26112. this._LODLevels.sort(function (a, b) {
  26113. if (a.distance < b.distance) {
  26114. return 1;
  26115. }
  26116. if (a.distance > b.distance) {
  26117. return -1;
  26118. }
  26119. return 0;
  26120. });
  26121. };
  26122. /**
  26123. * Add a mesh as LOD level triggered at the given distance.
  26124. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26125. * @param {number} distance The distance from the center of the object to show this level
  26126. * @param {Mesh} mesh The mesh to be added as LOD level
  26127. * @return {Mesh} This mesh (for chaining)
  26128. */
  26129. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26130. if (mesh && mesh._masterMesh) {
  26131. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26132. return this;
  26133. }
  26134. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26135. this._LODLevels.push(level);
  26136. if (mesh) {
  26137. mesh._masterMesh = this;
  26138. }
  26139. this._sortLODLevels();
  26140. return this;
  26141. };
  26142. /**
  26143. * Returns the LOD level mesh at the passed distance or null if not found.
  26144. * It is related to the method `addLODLevel(distance, mesh)`.
  26145. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26146. * Returns an object Mesh or `null`.
  26147. */
  26148. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26149. for (var index = 0; index < this._LODLevels.length; index++) {
  26150. var level = this._LODLevels[index];
  26151. if (level.distance === distance) {
  26152. return level.mesh;
  26153. }
  26154. }
  26155. return null;
  26156. };
  26157. /**
  26158. * Remove a mesh from the LOD array
  26159. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26160. * @param {Mesh} mesh The mesh to be removed.
  26161. * @return {Mesh} This mesh (for chaining)
  26162. */
  26163. Mesh.prototype.removeLODLevel = function (mesh) {
  26164. for (var index = 0; index < this._LODLevels.length; index++) {
  26165. if (this._LODLevels[index].mesh === mesh) {
  26166. this._LODLevels.splice(index, 1);
  26167. if (mesh) {
  26168. mesh._masterMesh = null;
  26169. }
  26170. }
  26171. }
  26172. this._sortLODLevels();
  26173. return this;
  26174. };
  26175. /**
  26176. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26177. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26178. */
  26179. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26180. if (!this._LODLevels || this._LODLevels.length === 0) {
  26181. return this;
  26182. }
  26183. var bSphere;
  26184. if (boundingSphere) {
  26185. bSphere = boundingSphere;
  26186. }
  26187. else {
  26188. var boundingInfo = this.getBoundingInfo();
  26189. bSphere = boundingInfo.boundingSphere;
  26190. }
  26191. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  26192. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  26193. if (this.onLODLevelSelection) {
  26194. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  26195. }
  26196. return this;
  26197. }
  26198. for (var index = 0; index < this._LODLevels.length; index++) {
  26199. var level = this._LODLevels[index];
  26200. if (level.distance < distanceToCamera) {
  26201. if (level.mesh) {
  26202. level.mesh._preActivate();
  26203. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  26204. }
  26205. if (this.onLODLevelSelection) {
  26206. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  26207. }
  26208. return level.mesh;
  26209. }
  26210. }
  26211. if (this.onLODLevelSelection) {
  26212. this.onLODLevelSelection(distanceToCamera, this, this);
  26213. }
  26214. return this;
  26215. };
  26216. Object.defineProperty(Mesh.prototype, "geometry", {
  26217. /**
  26218. * Returns the mesh internal Geometry object.
  26219. */
  26220. get: function () {
  26221. return this._geometry;
  26222. },
  26223. enumerable: true,
  26224. configurable: true
  26225. });
  26226. /**
  26227. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  26228. */
  26229. Mesh.prototype.getTotalVertices = function () {
  26230. if (this._geometry === null || this._geometry === undefined) {
  26231. return 0;
  26232. }
  26233. return this._geometry.getTotalVertices();
  26234. };
  26235. /**
  26236. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  26237. * 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.
  26238. * You can force the copy with forceCopy === true
  26239. * Returns null if the mesh has no geometry or no vertex buffer.
  26240. * Possible `kind` values :
  26241. * - BABYLON.VertexBuffer.PositionKind
  26242. * - BABYLON.VertexBuffer.UVKind
  26243. * - BABYLON.VertexBuffer.UV2Kind
  26244. * - BABYLON.VertexBuffer.UV3Kind
  26245. * - BABYLON.VertexBuffer.UV4Kind
  26246. * - BABYLON.VertexBuffer.UV5Kind
  26247. * - BABYLON.VertexBuffer.UV6Kind
  26248. * - BABYLON.VertexBuffer.ColorKind
  26249. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26250. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26251. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26252. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26253. */
  26254. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26255. if (!this._geometry) {
  26256. return null;
  26257. }
  26258. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  26259. };
  26260. /**
  26261. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26262. * Returns `null` if the mesh has no geometry.
  26263. * Possible `kind` values :
  26264. * - BABYLON.VertexBuffer.PositionKind
  26265. * - BABYLON.VertexBuffer.UVKind
  26266. * - BABYLON.VertexBuffer.UV2Kind
  26267. * - BABYLON.VertexBuffer.UV3Kind
  26268. * - BABYLON.VertexBuffer.UV4Kind
  26269. * - BABYLON.VertexBuffer.UV5Kind
  26270. * - BABYLON.VertexBuffer.UV6Kind
  26271. * - BABYLON.VertexBuffer.ColorKind
  26272. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26273. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26274. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26275. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26276. */
  26277. Mesh.prototype.getVertexBuffer = function (kind) {
  26278. if (!this._geometry) {
  26279. return null;
  26280. }
  26281. return this._geometry.getVertexBuffer(kind);
  26282. };
  26283. /**
  26284. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  26285. * Possible `kind` values :
  26286. * - BABYLON.VertexBuffer.PositionKind
  26287. * - BABYLON.VertexBuffer.UVKind
  26288. * - BABYLON.VertexBuffer.UV2Kind
  26289. * - BABYLON.VertexBuffer.UV3Kind
  26290. * - BABYLON.VertexBuffer.UV4Kind
  26291. * - BABYLON.VertexBuffer.UV5Kind
  26292. * - BABYLON.VertexBuffer.UV6Kind
  26293. * - BABYLON.VertexBuffer.ColorKind
  26294. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26295. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26296. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26297. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26298. */
  26299. Mesh.prototype.isVerticesDataPresent = function (kind) {
  26300. if (!this._geometry) {
  26301. if (this._delayInfo) {
  26302. return this._delayInfo.indexOf(kind) !== -1;
  26303. }
  26304. return false;
  26305. }
  26306. return this._geometry.isVerticesDataPresent(kind);
  26307. };
  26308. /**
  26309. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  26310. * Possible `kind` values :
  26311. * - BABYLON.VertexBuffer.PositionKind
  26312. * - BABYLON.VertexBuffer.UVKind
  26313. * - BABYLON.VertexBuffer.UV2Kind
  26314. * - BABYLON.VertexBuffer.UV3Kind
  26315. * - BABYLON.VertexBuffer.UV4Kind
  26316. * - BABYLON.VertexBuffer.UV5Kind
  26317. * - BABYLON.VertexBuffer.UV6Kind
  26318. * - BABYLON.VertexBuffer.ColorKind
  26319. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26320. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26321. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26322. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26323. */
  26324. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  26325. if (!this._geometry) {
  26326. if (this._delayInfo) {
  26327. return this._delayInfo.indexOf(kind) !== -1;
  26328. }
  26329. return false;
  26330. }
  26331. return this._geometry.isVertexBufferUpdatable(kind);
  26332. };
  26333. /**
  26334. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  26335. * Possible `kind` values :
  26336. * - BABYLON.VertexBuffer.PositionKind
  26337. * - BABYLON.VertexBuffer.UVKind
  26338. * - BABYLON.VertexBuffer.UV2Kind
  26339. * - BABYLON.VertexBuffer.UV3Kind
  26340. * - BABYLON.VertexBuffer.UV4Kind
  26341. * - BABYLON.VertexBuffer.UV5Kind
  26342. * - BABYLON.VertexBuffer.UV6Kind
  26343. * - BABYLON.VertexBuffer.ColorKind
  26344. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26345. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26346. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26347. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26348. */
  26349. Mesh.prototype.getVerticesDataKinds = function () {
  26350. if (!this._geometry) {
  26351. var result = new Array();
  26352. if (this._delayInfo) {
  26353. this._delayInfo.forEach(function (kind, index, array) {
  26354. result.push(kind);
  26355. });
  26356. }
  26357. return result;
  26358. }
  26359. return this._geometry.getVerticesDataKinds();
  26360. };
  26361. /**
  26362. * Returns a positive integer : the total number of indices in this mesh geometry.
  26363. * Returns zero if the mesh has no geometry.
  26364. */
  26365. Mesh.prototype.getTotalIndices = function () {
  26366. if (!this._geometry) {
  26367. return 0;
  26368. }
  26369. return this._geometry.getTotalIndices();
  26370. };
  26371. /**
  26372. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  26373. * 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.
  26374. * Returns an empty array if the mesh has no geometry.
  26375. */
  26376. Mesh.prototype.getIndices = function (copyWhenShared) {
  26377. if (!this._geometry) {
  26378. return [];
  26379. }
  26380. return this._geometry.getIndices(copyWhenShared);
  26381. };
  26382. Object.defineProperty(Mesh.prototype, "isBlocked", {
  26383. get: function () {
  26384. return this._masterMesh !== null && this._masterMesh !== undefined;
  26385. },
  26386. enumerable: true,
  26387. configurable: true
  26388. });
  26389. /**
  26390. * Determine if the current mesh is ready to be rendered
  26391. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  26392. * @returns true if all associated assets are ready (material, textures, shaders)
  26393. */
  26394. Mesh.prototype.isReady = function (forceInstanceSupport) {
  26395. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  26396. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26397. return false;
  26398. }
  26399. if (!_super.prototype.isReady.call(this)) {
  26400. return false;
  26401. }
  26402. if (!this.subMeshes || this.subMeshes.length === 0) {
  26403. return true;
  26404. }
  26405. var engine = this.getEngine();
  26406. var scene = this.getScene();
  26407. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  26408. this.computeWorldMatrix();
  26409. var mat = this.material || scene.defaultMaterial;
  26410. if (mat) {
  26411. if (mat.storeEffectOnSubMeshes) {
  26412. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26413. var subMesh = _a[_i];
  26414. var effectiveMaterial = subMesh.getMaterial();
  26415. if (effectiveMaterial) {
  26416. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26417. return false;
  26418. }
  26419. }
  26420. }
  26421. }
  26422. else {
  26423. if (!mat.isReady(this, hardwareInstancedRendering)) {
  26424. return false;
  26425. }
  26426. }
  26427. }
  26428. // Shadows
  26429. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  26430. var light = _c[_b];
  26431. var generator = light.getShadowGenerator();
  26432. if (generator) {
  26433. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  26434. var subMesh = _e[_d];
  26435. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  26436. return false;
  26437. }
  26438. }
  26439. }
  26440. }
  26441. // LOD
  26442. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  26443. var lod = _g[_f];
  26444. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  26445. return false;
  26446. }
  26447. }
  26448. return true;
  26449. };
  26450. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  26451. /**
  26452. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  26453. * This property is pertinent only for updatable parametric shapes.
  26454. */
  26455. get: function () {
  26456. return this._areNormalsFrozen;
  26457. },
  26458. enumerable: true,
  26459. configurable: true
  26460. });
  26461. /**
  26462. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26463. * It has no effect at all on other shapes.
  26464. * It prevents the mesh normals from being recomputed on next `positions` array update.
  26465. * Returns the Mesh.
  26466. */
  26467. Mesh.prototype.freezeNormals = function () {
  26468. this._areNormalsFrozen = true;
  26469. return this;
  26470. };
  26471. /**
  26472. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26473. * It has no effect at all on other shapes.
  26474. * It reactivates the mesh normals computation if it was previously frozen.
  26475. * Returns the Mesh.
  26476. */
  26477. Mesh.prototype.unfreezeNormals = function () {
  26478. this._areNormalsFrozen = false;
  26479. return this;
  26480. };
  26481. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  26482. /**
  26483. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  26484. */
  26485. set: function (count) {
  26486. this._overridenInstanceCount = count;
  26487. },
  26488. enumerable: true,
  26489. configurable: true
  26490. });
  26491. // Methods
  26492. Mesh.prototype._preActivate = function () {
  26493. var sceneRenderId = this.getScene().getRenderId();
  26494. if (this._preActivateId === sceneRenderId) {
  26495. return this;
  26496. }
  26497. this._preActivateId = sceneRenderId;
  26498. this._visibleInstances = null;
  26499. return this;
  26500. };
  26501. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  26502. if (this._visibleInstances) {
  26503. this._visibleInstances.intermediateDefaultRenderId = renderId;
  26504. }
  26505. return this;
  26506. };
  26507. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  26508. if (!this._visibleInstances) {
  26509. this._visibleInstances = {};
  26510. this._visibleInstances.defaultRenderId = renderId;
  26511. this._visibleInstances.selfDefaultRenderId = this._renderId;
  26512. }
  26513. if (!this._visibleInstances[renderId]) {
  26514. this._visibleInstances[renderId] = new Array();
  26515. }
  26516. this._visibleInstances[renderId].push(instance);
  26517. return this;
  26518. };
  26519. /**
  26520. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  26521. * This means the mesh underlying bounding box and sphere are recomputed.
  26522. * Returns the Mesh.
  26523. */
  26524. Mesh.prototype.refreshBoundingInfo = function () {
  26525. return this._refreshBoundingInfo(false);
  26526. };
  26527. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  26528. if (this._boundingInfo && this._boundingInfo.isLocked) {
  26529. return this;
  26530. }
  26531. var data = this._getPositionData(applySkeleton);
  26532. if (data) {
  26533. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  26534. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26535. }
  26536. if (this.subMeshes) {
  26537. for (var index = 0; index < this.subMeshes.length; index++) {
  26538. this.subMeshes[index].refreshBoundingInfo();
  26539. }
  26540. }
  26541. this._updateBoundingInfo();
  26542. return this;
  26543. };
  26544. Mesh.prototype._getPositionData = function (applySkeleton) {
  26545. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26546. if (data && applySkeleton && this.skeleton) {
  26547. data = BABYLON.Tools.Slice(data);
  26548. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26549. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26550. if (matricesWeightsData && matricesIndicesData) {
  26551. var needExtras = this.numBoneInfluencers > 4;
  26552. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26553. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26554. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  26555. var tempVector = BABYLON.Tmp.Vector3[0];
  26556. var finalMatrix = BABYLON.Tmp.Matrix[0];
  26557. var tempMatrix = BABYLON.Tmp.Matrix[1];
  26558. var matWeightIdx = 0;
  26559. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  26560. finalMatrix.reset();
  26561. var inf;
  26562. var weight;
  26563. for (inf = 0; inf < 4; inf++) {
  26564. weight = matricesWeightsData[matWeightIdx + inf];
  26565. if (weight <= 0)
  26566. break;
  26567. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26568. finalMatrix.addToSelf(tempMatrix);
  26569. }
  26570. if (needExtras) {
  26571. for (inf = 0; inf < 4; inf++) {
  26572. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26573. if (weight <= 0)
  26574. break;
  26575. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26576. finalMatrix.addToSelf(tempMatrix);
  26577. }
  26578. }
  26579. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  26580. tempVector.toArray(data, index);
  26581. }
  26582. }
  26583. }
  26584. return data;
  26585. };
  26586. Mesh.prototype._createGlobalSubMesh = function (force) {
  26587. var totalVertices = this.getTotalVertices();
  26588. if (!totalVertices || !this.getIndices()) {
  26589. return null;
  26590. }
  26591. // Check if we need to recreate the submeshes
  26592. if (this.subMeshes && this.subMeshes.length > 0) {
  26593. var ib = this.getIndices();
  26594. if (!ib) {
  26595. return null;
  26596. }
  26597. var totalIndices = ib.length;
  26598. var needToRecreate = false;
  26599. if (force) {
  26600. needToRecreate = true;
  26601. }
  26602. else {
  26603. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26604. var submesh = _a[_i];
  26605. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  26606. needToRecreate = true;
  26607. break;
  26608. }
  26609. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  26610. needToRecreate = true;
  26611. break;
  26612. }
  26613. }
  26614. }
  26615. if (!needToRecreate) {
  26616. return this.subMeshes[0];
  26617. }
  26618. }
  26619. this.releaseSubMeshes();
  26620. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  26621. };
  26622. Mesh.prototype.subdivide = function (count) {
  26623. if (count < 1) {
  26624. return;
  26625. }
  26626. var totalIndices = this.getTotalIndices();
  26627. var subdivisionSize = (totalIndices / count) | 0;
  26628. var offset = 0;
  26629. // Ensure that subdivisionSize is a multiple of 3
  26630. while (subdivisionSize % 3 !== 0) {
  26631. subdivisionSize++;
  26632. }
  26633. this.releaseSubMeshes();
  26634. for (var index = 0; index < count; index++) {
  26635. if (offset >= totalIndices) {
  26636. break;
  26637. }
  26638. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  26639. offset += subdivisionSize;
  26640. }
  26641. this.synchronizeInstances();
  26642. };
  26643. /**
  26644. * Sets the vertex data of the mesh geometry for the requested `kind`.
  26645. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  26646. * The `data` are either a numeric array either a Float32Array.
  26647. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  26648. * 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).
  26649. * Note that a new underlying VertexBuffer object is created each call.
  26650. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  26651. *
  26652. * Possible `kind` values :
  26653. * - BABYLON.VertexBuffer.PositionKind
  26654. * - BABYLON.VertexBuffer.UVKind
  26655. * - BABYLON.VertexBuffer.UV2Kind
  26656. * - BABYLON.VertexBuffer.UV3Kind
  26657. * - BABYLON.VertexBuffer.UV4Kind
  26658. * - BABYLON.VertexBuffer.UV5Kind
  26659. * - BABYLON.VertexBuffer.UV6Kind
  26660. * - BABYLON.VertexBuffer.ColorKind
  26661. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26662. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26663. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26664. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26665. *
  26666. * Returns the Mesh.
  26667. */
  26668. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26669. if (updatable === void 0) { updatable = false; }
  26670. if (!this._geometry) {
  26671. var vertexData = new BABYLON.VertexData();
  26672. vertexData.set(data, kind);
  26673. var scene = this.getScene();
  26674. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26675. }
  26676. else {
  26677. this._geometry.setVerticesData(kind, data, updatable, stride);
  26678. }
  26679. return this;
  26680. };
  26681. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  26682. if (updatable === void 0) { updatable = true; }
  26683. var vb = this.getVertexBuffer(kind);
  26684. if (!vb || vb.isUpdatable() === updatable) {
  26685. return;
  26686. }
  26687. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  26688. };
  26689. /**
  26690. * Sets the mesh VertexBuffer.
  26691. * Returns the Mesh.
  26692. */
  26693. Mesh.prototype.setVerticesBuffer = function (buffer) {
  26694. if (!this._geometry) {
  26695. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  26696. }
  26697. this._geometry.setVerticesBuffer(buffer);
  26698. return this;
  26699. };
  26700. /**
  26701. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  26702. * If the mesh has no geometry, it is simply returned as it is.
  26703. * The `data` are either a numeric array either a Float32Array.
  26704. * No new underlying VertexBuffer object is created.
  26705. * 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.
  26706. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  26707. *
  26708. * Possible `kind` values :
  26709. * - BABYLON.VertexBuffer.PositionKind
  26710. * - BABYLON.VertexBuffer.UVKind
  26711. * - BABYLON.VertexBuffer.UV2Kind
  26712. * - BABYLON.VertexBuffer.UV3Kind
  26713. * - BABYLON.VertexBuffer.UV4Kind
  26714. * - BABYLON.VertexBuffer.UV5Kind
  26715. * - BABYLON.VertexBuffer.UV6Kind
  26716. * - BABYLON.VertexBuffer.ColorKind
  26717. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26718. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26719. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26720. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26721. *
  26722. * Returns the Mesh.
  26723. */
  26724. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  26725. if (!this._geometry) {
  26726. return this;
  26727. }
  26728. if (!makeItUnique) {
  26729. this._geometry.updateVerticesData(kind, data, updateExtends);
  26730. }
  26731. else {
  26732. this.makeGeometryUnique();
  26733. this.updateVerticesData(kind, data, updateExtends, false);
  26734. }
  26735. return this;
  26736. };
  26737. /**
  26738. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  26739. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  26740. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  26741. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  26742. * Returns the Mesh.
  26743. */
  26744. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  26745. if (computeNormals === void 0) { computeNormals = true; }
  26746. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26747. if (!positions) {
  26748. return this;
  26749. }
  26750. positionFunction(positions);
  26751. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26752. if (computeNormals) {
  26753. var indices = this.getIndices();
  26754. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26755. if (!normals) {
  26756. return this;
  26757. }
  26758. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26759. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26760. }
  26761. return this;
  26762. };
  26763. /**
  26764. * Creates a un-shared specific occurence of the geometry for the mesh.
  26765. * Returns the Mesh.
  26766. */
  26767. Mesh.prototype.makeGeometryUnique = function () {
  26768. if (!this._geometry) {
  26769. return this;
  26770. }
  26771. var oldGeometry = this._geometry;
  26772. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26773. oldGeometry.releaseForMesh(this, true);
  26774. geometry.applyToMesh(this);
  26775. return this;
  26776. };
  26777. /**
  26778. * Sets the mesh indices.
  26779. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26780. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26781. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26782. * This method creates a new index buffer each call.
  26783. * Returns the Mesh.
  26784. */
  26785. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26786. if (totalVertices === void 0) { totalVertices = null; }
  26787. if (updatable === void 0) { updatable = false; }
  26788. if (!this._geometry) {
  26789. var vertexData = new BABYLON.VertexData();
  26790. vertexData.indices = indices;
  26791. var scene = this.getScene();
  26792. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26793. }
  26794. else {
  26795. this._geometry.setIndices(indices, totalVertices, updatable);
  26796. }
  26797. return this;
  26798. };
  26799. /**
  26800. * Update the current index buffer
  26801. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26802. * Returns the Mesh.
  26803. */
  26804. Mesh.prototype.updateIndices = function (indices, offset) {
  26805. if (!this._geometry) {
  26806. return this;
  26807. }
  26808. this._geometry.updateIndices(indices, offset);
  26809. return this;
  26810. };
  26811. /**
  26812. * Invert the geometry to move from a right handed system to a left handed one.
  26813. * Returns the Mesh.
  26814. */
  26815. Mesh.prototype.toLeftHanded = function () {
  26816. if (!this._geometry) {
  26817. return this;
  26818. }
  26819. this._geometry.toLeftHanded();
  26820. return this;
  26821. };
  26822. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26823. if (!this._geometry) {
  26824. return this;
  26825. }
  26826. var engine = this.getScene().getEngine();
  26827. // Wireframe
  26828. var indexToBind;
  26829. if (this._unIndexed) {
  26830. indexToBind = null;
  26831. }
  26832. else {
  26833. switch (fillMode) {
  26834. case BABYLON.Material.PointFillMode:
  26835. indexToBind = null;
  26836. break;
  26837. case BABYLON.Material.WireFrameFillMode:
  26838. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26839. break;
  26840. default:
  26841. case BABYLON.Material.TriangleFillMode:
  26842. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26843. break;
  26844. }
  26845. }
  26846. // VBOs
  26847. this._geometry._bind(effect, indexToBind);
  26848. return this;
  26849. };
  26850. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26851. if (alternate === void 0) { alternate = false; }
  26852. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26853. return this;
  26854. }
  26855. this.onBeforeDrawObservable.notifyObservers(this);
  26856. var scene = this.getScene();
  26857. var engine = scene.getEngine();
  26858. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26859. // or triangles as points
  26860. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26861. }
  26862. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26863. // Triangles as wireframe
  26864. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26865. }
  26866. else {
  26867. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26868. }
  26869. if (scene._isAlternateRenderingEnabled && !alternate) {
  26870. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26871. if (!effect || !scene.activeCamera) {
  26872. return this;
  26873. }
  26874. scene._switchToAlternateCameraConfiguration(true);
  26875. this._effectiveMaterial.bindView(effect);
  26876. this._effectiveMaterial.bindViewProjection(effect);
  26877. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26878. this._draw(subMesh, fillMode, instancesCount, true);
  26879. engine.setViewport(scene.activeCamera.viewport);
  26880. scene._switchToAlternateCameraConfiguration(false);
  26881. this._effectiveMaterial.bindView(effect);
  26882. this._effectiveMaterial.bindViewProjection(effect);
  26883. }
  26884. return this;
  26885. };
  26886. /**
  26887. * Registers for this mesh a javascript function called just before the rendering process.
  26888. * This function is passed the current mesh.
  26889. * Return the Mesh.
  26890. */
  26891. Mesh.prototype.registerBeforeRender = function (func) {
  26892. this.onBeforeRenderObservable.add(func);
  26893. return this;
  26894. };
  26895. /**
  26896. * Disposes a previously registered javascript function called before the rendering.
  26897. * This function is passed the current mesh.
  26898. * Returns the Mesh.
  26899. */
  26900. Mesh.prototype.unregisterBeforeRender = function (func) {
  26901. this.onBeforeRenderObservable.removeCallback(func);
  26902. return this;
  26903. };
  26904. /**
  26905. * Registers for this mesh a javascript function called just after the rendering is complete.
  26906. * This function is passed the current mesh.
  26907. * Returns the Mesh.
  26908. */
  26909. Mesh.prototype.registerAfterRender = function (func) {
  26910. this.onAfterRenderObservable.add(func);
  26911. return this;
  26912. };
  26913. /**
  26914. * Disposes a previously registered javascript function called after the rendering.
  26915. * This function is passed the current mesh.
  26916. * Return the Mesh.
  26917. */
  26918. Mesh.prototype.unregisterAfterRender = function (func) {
  26919. this.onAfterRenderObservable.removeCallback(func);
  26920. return this;
  26921. };
  26922. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26923. var scene = this.getScene();
  26924. this._batchCache.mustReturn = false;
  26925. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26926. this._batchCache.visibleInstances[subMeshId] = null;
  26927. if (this._visibleInstances) {
  26928. var currentRenderId = scene.getRenderId();
  26929. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26930. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26931. var selfRenderId = this._renderId;
  26932. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26933. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26934. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26935. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26936. }
  26937. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26938. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26939. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26940. this._batchCache.mustReturn = true;
  26941. return this._batchCache;
  26942. }
  26943. if (currentRenderId !== selfRenderId) {
  26944. this._batchCache.renderSelf[subMeshId] = false;
  26945. }
  26946. }
  26947. this._renderIdForInstances[subMeshId] = currentRenderId;
  26948. }
  26949. return this._batchCache;
  26950. };
  26951. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26952. var visibleInstances = batch.visibleInstances[subMesh._id];
  26953. if (!visibleInstances) {
  26954. return this;
  26955. }
  26956. var matricesCount = visibleInstances.length + 1;
  26957. var bufferSize = matricesCount * 16 * 4;
  26958. var currentInstancesBufferSize = this._instancesBufferSize;
  26959. var instancesBuffer = this._instancesBuffer;
  26960. while (this._instancesBufferSize < bufferSize) {
  26961. this._instancesBufferSize *= 2;
  26962. }
  26963. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26964. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26965. }
  26966. var offset = 0;
  26967. var instancesCount = 0;
  26968. var world = this.getWorldMatrix();
  26969. if (batch.renderSelf[subMesh._id]) {
  26970. world.copyToArray(this._instancesData, offset);
  26971. offset += 16;
  26972. instancesCount++;
  26973. }
  26974. if (visibleInstances) {
  26975. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26976. var instance = visibleInstances[instanceIndex];
  26977. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26978. offset += 16;
  26979. instancesCount++;
  26980. }
  26981. }
  26982. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26983. if (instancesBuffer) {
  26984. instancesBuffer.dispose();
  26985. }
  26986. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26987. this._instancesBuffer = instancesBuffer;
  26988. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26989. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26990. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26991. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26992. }
  26993. else {
  26994. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26995. }
  26996. this._bind(subMesh, effect, fillMode);
  26997. this._draw(subMesh, fillMode, instancesCount);
  26998. engine.unbindInstanceAttributes();
  26999. return this;
  27000. };
  27001. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27002. var scene = this.getScene();
  27003. var engine = scene.getEngine();
  27004. if (hardwareInstancedRendering) {
  27005. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27006. }
  27007. else {
  27008. if (batch.renderSelf[subMesh._id]) {
  27009. // Draw
  27010. if (onBeforeDraw) {
  27011. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27012. }
  27013. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27014. }
  27015. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27016. if (visibleInstancesForSubMesh) {
  27017. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27018. var instance = visibleInstancesForSubMesh[instanceIndex];
  27019. // World
  27020. var world = instance.getWorldMatrix();
  27021. if (onBeforeDraw) {
  27022. onBeforeDraw(true, world, effectiveMaterial);
  27023. }
  27024. // Draw
  27025. this._draw(subMesh, fillMode);
  27026. }
  27027. }
  27028. }
  27029. return this;
  27030. };
  27031. /**
  27032. * Triggers the draw call for the mesh.
  27033. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  27034. * Returns the Mesh.
  27035. */
  27036. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  27037. this.checkOcclusionQuery();
  27038. if (this._isOccluded) {
  27039. return this;
  27040. }
  27041. var scene = this.getScene();
  27042. // Managing instances
  27043. var batch = this._getInstancesRenderList(subMesh._id);
  27044. if (batch.mustReturn) {
  27045. return this;
  27046. }
  27047. // Checking geometry state
  27048. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27049. return this;
  27050. }
  27051. this.onBeforeRenderObservable.notifyObservers(this);
  27052. var engine = scene.getEngine();
  27053. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27054. // Material
  27055. var material = subMesh.getMaterial();
  27056. if (!material) {
  27057. return this;
  27058. }
  27059. this._effectiveMaterial = material;
  27060. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27061. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27062. return this;
  27063. }
  27064. }
  27065. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  27066. return this;
  27067. }
  27068. // Alpha mode
  27069. if (enableAlphaMode) {
  27070. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  27071. }
  27072. // Outline - step 1
  27073. var savedDepthWrite = engine.getDepthWrite();
  27074. if (this.renderOutline) {
  27075. engine.setDepthWrite(false);
  27076. scene.getOutlineRenderer().render(subMesh, batch);
  27077. engine.setDepthWrite(savedDepthWrite);
  27078. }
  27079. var effect;
  27080. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27081. effect = subMesh.effect;
  27082. }
  27083. else {
  27084. effect = this._effectiveMaterial.getEffect();
  27085. }
  27086. if (!effect) {
  27087. return this;
  27088. }
  27089. var sideOrientation = this.overrideMaterialSideOrientation;
  27090. if (sideOrientation == null) {
  27091. sideOrientation = this._effectiveMaterial.sideOrientation;
  27092. if (this._getWorldMatrixDeterminant() < 0) {
  27093. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  27094. }
  27095. }
  27096. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  27097. if (this._effectiveMaterial.forceDepthWrite) {
  27098. engine.setDepthWrite(true);
  27099. }
  27100. // Bind
  27101. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  27102. if (!hardwareInstancedRendering) {
  27103. this._bind(subMesh, effect, fillMode);
  27104. }
  27105. var world = this.getWorldMatrix();
  27106. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27107. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27108. }
  27109. else {
  27110. this._effectiveMaterial.bind(world, this);
  27111. }
  27112. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27113. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27114. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27115. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27116. }
  27117. // Draw
  27118. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27119. // Unbind
  27120. this._effectiveMaterial.unbind();
  27121. // Outline - step 2
  27122. if (this.renderOutline && savedDepthWrite) {
  27123. engine.setDepthWrite(true);
  27124. engine.setColorWrite(false);
  27125. scene.getOutlineRenderer().render(subMesh, batch);
  27126. engine.setColorWrite(true);
  27127. }
  27128. // Overlay
  27129. if (this.renderOverlay) {
  27130. var currentMode = engine.getAlphaMode();
  27131. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27132. scene.getOutlineRenderer().render(subMesh, batch, true);
  27133. engine.setAlphaMode(currentMode);
  27134. }
  27135. this.onAfterRenderObservable.notifyObservers(this);
  27136. return this;
  27137. };
  27138. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27139. if (isInstance && effectiveMaterial) {
  27140. effectiveMaterial.bindOnlyWorldMatrix(world);
  27141. }
  27142. };
  27143. /**
  27144. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27145. */
  27146. Mesh.prototype.getEmittedParticleSystems = function () {
  27147. var results = new Array();
  27148. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27149. var particleSystem = this.getScene().particleSystems[index];
  27150. if (particleSystem.emitter === this) {
  27151. results.push(particleSystem);
  27152. }
  27153. }
  27154. return results;
  27155. };
  27156. /**
  27157. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27158. */
  27159. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27160. var results = new Array();
  27161. var descendants = this.getDescendants();
  27162. descendants.push(this);
  27163. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27164. var particleSystem = this.getScene().particleSystems[index];
  27165. var emitter = particleSystem.emitter;
  27166. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27167. results.push(particleSystem);
  27168. }
  27169. }
  27170. return results;
  27171. };
  27172. Mesh.prototype._checkDelayState = function () {
  27173. var scene = this.getScene();
  27174. if (this._geometry) {
  27175. this._geometry.load(scene);
  27176. }
  27177. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27178. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27179. this._queueLoad(scene);
  27180. }
  27181. return this;
  27182. };
  27183. Mesh.prototype._queueLoad = function (scene) {
  27184. var _this = this;
  27185. scene._addPendingData(this);
  27186. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  27187. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27188. if (data instanceof ArrayBuffer) {
  27189. _this._delayLoadingFunction(data, _this);
  27190. }
  27191. else {
  27192. _this._delayLoadingFunction(JSON.parse(data), _this);
  27193. }
  27194. _this.instances.forEach(function (instance) {
  27195. instance._syncSubMeshes();
  27196. });
  27197. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27198. scene._removePendingData(_this);
  27199. }, function () { }, scene.database, getBinaryData);
  27200. return this;
  27201. };
  27202. /**
  27203. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  27204. */
  27205. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  27206. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27207. return false;
  27208. }
  27209. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  27210. return false;
  27211. }
  27212. this._checkDelayState();
  27213. return true;
  27214. };
  27215. /**
  27216. * Sets the mesh material by the material or multiMaterial `id` property.
  27217. * The material `id` is a string identifying the material or the multiMaterial.
  27218. * This method returns the Mesh.
  27219. */
  27220. Mesh.prototype.setMaterialByID = function (id) {
  27221. var materials = this.getScene().materials;
  27222. var index;
  27223. for (index = materials.length - 1; index > -1; index--) {
  27224. if (materials[index].id === id) {
  27225. this.material = materials[index];
  27226. return this;
  27227. }
  27228. }
  27229. // Multi
  27230. var multiMaterials = this.getScene().multiMaterials;
  27231. for (index = multiMaterials.length - 1; index > -1; index--) {
  27232. if (multiMaterials[index].id === id) {
  27233. this.material = multiMaterials[index];
  27234. return this;
  27235. }
  27236. }
  27237. return this;
  27238. };
  27239. /**
  27240. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  27241. */
  27242. Mesh.prototype.getAnimatables = function () {
  27243. var results = new Array();
  27244. if (this.material) {
  27245. results.push(this.material);
  27246. }
  27247. if (this.skeleton) {
  27248. results.push(this.skeleton);
  27249. }
  27250. return results;
  27251. };
  27252. /**
  27253. * Modifies the mesh geometry according to the passed transformation matrix.
  27254. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  27255. * The mesh normals are modified accordingly the same transformation.
  27256. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  27257. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27258. * Returns the Mesh.
  27259. */
  27260. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27261. // Position
  27262. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27263. return this;
  27264. }
  27265. var submeshes = this.subMeshes.splice(0);
  27266. this._resetPointsArrayCache();
  27267. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27268. var temp = new Array();
  27269. var index;
  27270. for (index = 0; index < data.length; index += 3) {
  27271. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27272. }
  27273. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27274. // Normals
  27275. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27276. return this;
  27277. }
  27278. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27279. temp = [];
  27280. for (index = 0; index < data.length; index += 3) {
  27281. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27282. }
  27283. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  27284. // flip faces?
  27285. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  27286. this.flipFaces();
  27287. }
  27288. // Restore submeshes
  27289. this.releaseSubMeshes();
  27290. this.subMeshes = submeshes;
  27291. return this;
  27292. };
  27293. /**
  27294. * Modifies the mesh geometry according to its own current World Matrix.
  27295. * The mesh World Matrix is then reset.
  27296. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  27297. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  27298. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27299. * Returns the Mesh.
  27300. */
  27301. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  27302. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  27303. this.scaling.copyFromFloats(1, 1, 1);
  27304. this.position.copyFromFloats(0, 0, 0);
  27305. this.rotation.copyFromFloats(0, 0, 0);
  27306. //only if quaternion is already set
  27307. if (this.rotationQuaternion) {
  27308. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  27309. }
  27310. this._worldMatrix = BABYLON.Matrix.Identity();
  27311. return this;
  27312. };
  27313. Object.defineProperty(Mesh.prototype, "_positions", {
  27314. // Cache
  27315. get: function () {
  27316. if (this._geometry) {
  27317. return this._geometry._positions;
  27318. }
  27319. return null;
  27320. },
  27321. enumerable: true,
  27322. configurable: true
  27323. });
  27324. Mesh.prototype._resetPointsArrayCache = function () {
  27325. if (this._geometry) {
  27326. this._geometry._resetPointsArrayCache();
  27327. }
  27328. return this;
  27329. };
  27330. Mesh.prototype._generatePointsArray = function () {
  27331. if (this._geometry) {
  27332. return this._geometry._generatePointsArray();
  27333. }
  27334. return false;
  27335. };
  27336. /**
  27337. * Returns a new Mesh object generated from the current mesh properties.
  27338. * This method must not get confused with createInstance().
  27339. * The parameter `name` is a string, the name given to the new mesh.
  27340. * The optional parameter `newParent` can be any Node object (default `null`).
  27341. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  27342. * 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.
  27343. */
  27344. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  27345. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27346. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  27347. };
  27348. /**
  27349. * Disposes the Mesh.
  27350. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  27351. * Returns nothing.
  27352. */
  27353. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  27354. var _this = this;
  27355. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  27356. this.morphTargetManager = null;
  27357. if (this._geometry) {
  27358. this._geometry.releaseForMesh(this, true);
  27359. }
  27360. // Sources
  27361. var meshes = this.getScene().meshes;
  27362. meshes.forEach(function (abstractMesh) {
  27363. var mesh = abstractMesh;
  27364. if (mesh._source && mesh._source === _this) {
  27365. mesh._source = null;
  27366. }
  27367. });
  27368. this._source = null;
  27369. // Instances
  27370. if (this._instancesBuffer) {
  27371. this._instancesBuffer.dispose();
  27372. this._instancesBuffer = null;
  27373. }
  27374. while (this.instances.length) {
  27375. this.instances[0].dispose();
  27376. }
  27377. // Highlight layers.
  27378. var highlightLayers = this.getScene().highlightLayers;
  27379. for (var i = 0; i < highlightLayers.length; i++) {
  27380. var highlightLayer = highlightLayers[i];
  27381. if (highlightLayer) {
  27382. highlightLayer.removeMesh(this);
  27383. highlightLayer.removeExcludedMesh(this);
  27384. }
  27385. }
  27386. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  27387. };
  27388. /**
  27389. * Modifies the mesh geometry according to a displacement map.
  27390. * 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.
  27391. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27392. * This method returns nothing.
  27393. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  27394. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27395. * 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.
  27396. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27397. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27398. *
  27399. * Returns the Mesh.
  27400. */
  27401. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  27402. var _this = this;
  27403. var scene = this.getScene();
  27404. var onload = function (img) {
  27405. // Getting height map data
  27406. var canvas = document.createElement("canvas");
  27407. var context = canvas.getContext("2d");
  27408. var heightMapWidth = img.width;
  27409. var heightMapHeight = img.height;
  27410. canvas.width = heightMapWidth;
  27411. canvas.height = heightMapHeight;
  27412. context.drawImage(img, 0, 0);
  27413. // Create VertexData from map data
  27414. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  27415. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  27416. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  27417. //execute success callback, if set
  27418. if (onSuccess) {
  27419. onSuccess(_this);
  27420. }
  27421. };
  27422. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  27423. return this;
  27424. };
  27425. /**
  27426. * Modifies the mesh geometry according to a displacementMap buffer.
  27427. * 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.
  27428. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27429. * This method returns nothing.
  27430. * 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.
  27431. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  27432. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27433. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27434. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27435. *
  27436. * Returns the Mesh.
  27437. */
  27438. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  27439. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  27440. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  27441. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27442. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  27443. return this;
  27444. }
  27445. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27446. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27447. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27448. var position = BABYLON.Vector3.Zero();
  27449. var normal = BABYLON.Vector3.Zero();
  27450. var uv = BABYLON.Vector2.Zero();
  27451. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  27452. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  27453. for (var index = 0; index < positions.length; index += 3) {
  27454. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  27455. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  27456. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  27457. // Compute height
  27458. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  27459. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  27460. var pos = (u + v * heightMapWidth) * 4;
  27461. var r = buffer[pos] / 255.0;
  27462. var g = buffer[pos + 1] / 255.0;
  27463. var b = buffer[pos + 2] / 255.0;
  27464. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27465. normal.normalize();
  27466. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  27467. position = position.add(normal);
  27468. position.toArray(positions, index);
  27469. }
  27470. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  27471. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  27472. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  27473. return this;
  27474. };
  27475. /**
  27476. * Modify the mesh to get a flat shading rendering.
  27477. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  27478. * This method returns the Mesh.
  27479. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  27480. */
  27481. Mesh.prototype.convertToFlatShadedMesh = function () {
  27482. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  27483. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27484. var kinds = this.getVerticesDataKinds();
  27485. var vbs = {};
  27486. var data = {};
  27487. var newdata = {};
  27488. var updatableNormals = false;
  27489. var kindIndex;
  27490. var kind;
  27491. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27492. kind = kinds[kindIndex];
  27493. var vertexBuffer = this.getVertexBuffer(kind);
  27494. if (kind === BABYLON.VertexBuffer.NormalKind) {
  27495. updatableNormals = vertexBuffer.isUpdatable();
  27496. kinds.splice(kindIndex, 1);
  27497. kindIndex--;
  27498. continue;
  27499. }
  27500. vbs[kind] = vertexBuffer;
  27501. data[kind] = vbs[kind].getData();
  27502. newdata[kind] = [];
  27503. }
  27504. // Save previous submeshes
  27505. var previousSubmeshes = this.subMeshes.slice(0);
  27506. var indices = this.getIndices();
  27507. var totalIndices = this.getTotalIndices();
  27508. // Generating unique vertices per face
  27509. var index;
  27510. for (index = 0; index < totalIndices; index++) {
  27511. var vertexIndex = indices[index];
  27512. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27513. kind = kinds[kindIndex];
  27514. var stride = vbs[kind].getStrideSize();
  27515. for (var offset = 0; offset < stride; offset++) {
  27516. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27517. }
  27518. }
  27519. }
  27520. // Updating faces & normal
  27521. var normals = [];
  27522. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  27523. for (index = 0; index < totalIndices; index += 3) {
  27524. indices[index] = index;
  27525. indices[index + 1] = index + 1;
  27526. indices[index + 2] = index + 2;
  27527. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  27528. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  27529. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  27530. var p1p2 = p1.subtract(p2);
  27531. var p3p2 = p3.subtract(p2);
  27532. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  27533. // Store same normals for every vertex
  27534. for (var localIndex = 0; localIndex < 3; localIndex++) {
  27535. normals.push(normal.x);
  27536. normals.push(normal.y);
  27537. normals.push(normal.z);
  27538. }
  27539. }
  27540. this.setIndices(indices);
  27541. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  27542. // Updating vertex buffers
  27543. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27544. kind = kinds[kindIndex];
  27545. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27546. }
  27547. // Updating submeshes
  27548. this.releaseSubMeshes();
  27549. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27550. var previousOne = previousSubmeshes[submeshIndex];
  27551. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27552. }
  27553. this.synchronizeInstances();
  27554. return this;
  27555. };
  27556. /**
  27557. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  27558. * In other words, more vertices, no more indices and a single bigger VBO.
  27559. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  27560. * Returns the Mesh.
  27561. */
  27562. Mesh.prototype.convertToUnIndexedMesh = function () {
  27563. /// <summary>Remove indices by unfolding faces into buffers</summary>
  27564. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27565. var kinds = this.getVerticesDataKinds();
  27566. var vbs = {};
  27567. var data = {};
  27568. var newdata = {};
  27569. var kindIndex;
  27570. var kind;
  27571. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27572. kind = kinds[kindIndex];
  27573. var vertexBuffer = this.getVertexBuffer(kind);
  27574. vbs[kind] = vertexBuffer;
  27575. data[kind] = vbs[kind].getData();
  27576. newdata[kind] = [];
  27577. }
  27578. // Save previous submeshes
  27579. var previousSubmeshes = this.subMeshes.slice(0);
  27580. var indices = this.getIndices();
  27581. var totalIndices = this.getTotalIndices();
  27582. // Generating unique vertices per face
  27583. var index;
  27584. for (index = 0; index < totalIndices; index++) {
  27585. var vertexIndex = indices[index];
  27586. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27587. kind = kinds[kindIndex];
  27588. var stride = vbs[kind].getStrideSize();
  27589. for (var offset = 0; offset < stride; offset++) {
  27590. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27591. }
  27592. }
  27593. }
  27594. // Updating indices
  27595. for (index = 0; index < totalIndices; index += 3) {
  27596. indices[index] = index;
  27597. indices[index + 1] = index + 1;
  27598. indices[index + 2] = index + 2;
  27599. }
  27600. this.setIndices(indices);
  27601. // Updating vertex buffers
  27602. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27603. kind = kinds[kindIndex];
  27604. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27605. }
  27606. // Updating submeshes
  27607. this.releaseSubMeshes();
  27608. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27609. var previousOne = previousSubmeshes[submeshIndex];
  27610. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27611. }
  27612. this._unIndexed = true;
  27613. this.synchronizeInstances();
  27614. return this;
  27615. };
  27616. /**
  27617. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  27618. * This method returns the Mesh.
  27619. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  27620. */
  27621. Mesh.prototype.flipFaces = function (flipNormals) {
  27622. if (flipNormals === void 0) { flipNormals = false; }
  27623. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  27624. var i;
  27625. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  27626. for (i = 0; i < vertex_data.normals.length; i++) {
  27627. vertex_data.normals[i] *= -1;
  27628. }
  27629. }
  27630. if (vertex_data.indices) {
  27631. var temp;
  27632. for (i = 0; i < vertex_data.indices.length; i += 3) {
  27633. // reassign indices
  27634. temp = vertex_data.indices[i + 1];
  27635. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  27636. vertex_data.indices[i + 2] = temp;
  27637. }
  27638. }
  27639. vertex_data.applyToMesh(this);
  27640. return this;
  27641. };
  27642. // Instances
  27643. /**
  27644. * Creates a new InstancedMesh object from the mesh model.
  27645. * An instance shares the same properties and the same material than its model.
  27646. * Only these properties of each instance can then be set individually :
  27647. * - position
  27648. * - rotation
  27649. * - rotationQuaternion
  27650. * - setPivotMatrix
  27651. * - scaling
  27652. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  27653. * Warning : this method is not supported for Line mesh and LineSystem
  27654. */
  27655. Mesh.prototype.createInstance = function (name) {
  27656. return new BABYLON.InstancedMesh(name, this);
  27657. };
  27658. /**
  27659. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  27660. * After this call, all the mesh instances have the same submeshes than the current mesh.
  27661. * This method returns the Mesh.
  27662. */
  27663. Mesh.prototype.synchronizeInstances = function () {
  27664. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  27665. var instance = this.instances[instanceIndex];
  27666. instance._syncSubMeshes();
  27667. }
  27668. return this;
  27669. };
  27670. /**
  27671. * Simplify the mesh according to the given array of settings.
  27672. * Function will return immediately and will simplify async. It returns the Mesh.
  27673. * @param settings a collection of simplification settings.
  27674. * @param parallelProcessing should all levels calculate parallel or one after the other.
  27675. * @param type the type of simplification to run.
  27676. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  27677. */
  27678. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  27679. if (parallelProcessing === void 0) { parallelProcessing = true; }
  27680. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  27681. this.getScene().simplificationQueue.addTask({
  27682. settings: settings,
  27683. parallelProcessing: parallelProcessing,
  27684. mesh: this,
  27685. simplificationType: simplificationType,
  27686. successCallback: successCallback
  27687. });
  27688. return this;
  27689. };
  27690. /**
  27691. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  27692. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  27693. * This should be used together with the simplification to avoid disappearing triangles.
  27694. * Returns the Mesh.
  27695. * @param successCallback an optional success callback to be called after the optimization finished.
  27696. */
  27697. Mesh.prototype.optimizeIndices = function (successCallback) {
  27698. var _this = this;
  27699. var indices = this.getIndices();
  27700. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27701. if (!positions || !indices) {
  27702. return this;
  27703. }
  27704. var vectorPositions = new Array();
  27705. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  27706. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  27707. }
  27708. var dupes = new Array();
  27709. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  27710. var realPos = vectorPositions.length - 1 - iteration;
  27711. var testedPosition = vectorPositions[realPos];
  27712. for (var j = 0; j < realPos; ++j) {
  27713. var againstPosition = vectorPositions[j];
  27714. if (testedPosition.equals(againstPosition)) {
  27715. dupes[realPos] = j;
  27716. break;
  27717. }
  27718. }
  27719. }, function () {
  27720. for (var i = 0; i < indices.length; ++i) {
  27721. indices[i] = dupes[indices[i]] || indices[i];
  27722. }
  27723. //indices are now reordered
  27724. var originalSubMeshes = _this.subMeshes.slice(0);
  27725. _this.setIndices(indices);
  27726. _this.subMeshes = originalSubMeshes;
  27727. if (successCallback) {
  27728. successCallback(_this);
  27729. }
  27730. });
  27731. return this;
  27732. };
  27733. Mesh.prototype.serialize = function (serializationObject) {
  27734. serializationObject.name = this.name;
  27735. serializationObject.id = this.id;
  27736. serializationObject.type = this.getClassName();
  27737. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27738. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27739. }
  27740. serializationObject.position = this.position.asArray();
  27741. if (this.rotationQuaternion) {
  27742. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  27743. }
  27744. else if (this.rotation) {
  27745. serializationObject.rotation = this.rotation.asArray();
  27746. }
  27747. serializationObject.scaling = this.scaling.asArray();
  27748. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  27749. serializationObject.isEnabled = this.isEnabled(false);
  27750. serializationObject.isVisible = this.isVisible;
  27751. serializationObject.infiniteDistance = this.infiniteDistance;
  27752. serializationObject.pickable = this.isPickable;
  27753. serializationObject.receiveShadows = this.receiveShadows;
  27754. serializationObject.billboardMode = this.billboardMode;
  27755. serializationObject.visibility = this.visibility;
  27756. serializationObject.checkCollisions = this.checkCollisions;
  27757. serializationObject.isBlocker = this.isBlocker;
  27758. // Parent
  27759. if (this.parent) {
  27760. serializationObject.parentId = this.parent.id;
  27761. }
  27762. // Geometry
  27763. serializationObject.isUnIndexed = this.isUnIndexed;
  27764. var geometry = this._geometry;
  27765. if (geometry) {
  27766. var geometryId = geometry.id;
  27767. serializationObject.geometryId = geometryId;
  27768. // SubMeshes
  27769. serializationObject.subMeshes = [];
  27770. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27771. var subMesh = this.subMeshes[subIndex];
  27772. serializationObject.subMeshes.push({
  27773. materialIndex: subMesh.materialIndex,
  27774. verticesStart: subMesh.verticesStart,
  27775. verticesCount: subMesh.verticesCount,
  27776. indexStart: subMesh.indexStart,
  27777. indexCount: subMesh.indexCount
  27778. });
  27779. }
  27780. }
  27781. // Material
  27782. if (this.material) {
  27783. serializationObject.materialId = this.material.id;
  27784. }
  27785. else {
  27786. this.material = null;
  27787. }
  27788. // Morph targets
  27789. if (this.morphTargetManager) {
  27790. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27791. }
  27792. // Skeleton
  27793. if (this.skeleton) {
  27794. serializationObject.skeletonId = this.skeleton.id;
  27795. }
  27796. // Physics
  27797. //TODO implement correct serialization for physics impostors.
  27798. var impostor = this.getPhysicsImpostor();
  27799. if (impostor) {
  27800. serializationObject.physicsMass = impostor.getParam("mass");
  27801. serializationObject.physicsFriction = impostor.getParam("friction");
  27802. serializationObject.physicsRestitution = impostor.getParam("mass");
  27803. serializationObject.physicsImpostor = impostor.type;
  27804. }
  27805. // Metadata
  27806. if (this.metadata) {
  27807. serializationObject.metadata = this.metadata;
  27808. }
  27809. // Instances
  27810. serializationObject.instances = [];
  27811. for (var index = 0; index < this.instances.length; index++) {
  27812. var instance = this.instances[index];
  27813. var serializationInstance = {
  27814. name: instance.name,
  27815. id: instance.id,
  27816. position: instance.position.asArray(),
  27817. scaling: instance.scaling.asArray()
  27818. };
  27819. if (instance.rotationQuaternion) {
  27820. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27821. }
  27822. else if (instance.rotation) {
  27823. serializationInstance.rotation = instance.rotation.asArray();
  27824. }
  27825. serializationObject.instances.push(serializationInstance);
  27826. // Animations
  27827. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27828. serializationInstance.ranges = instance.serializeAnimationRanges();
  27829. }
  27830. //
  27831. // Animations
  27832. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27833. serializationObject.ranges = this.serializeAnimationRanges();
  27834. // Layer mask
  27835. serializationObject.layerMask = this.layerMask;
  27836. // Alpha
  27837. serializationObject.alphaIndex = this.alphaIndex;
  27838. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27839. // Overlay
  27840. serializationObject.overlayAlpha = this.overlayAlpha;
  27841. serializationObject.overlayColor = this.overlayColor.asArray();
  27842. serializationObject.renderOverlay = this.renderOverlay;
  27843. // Fog
  27844. serializationObject.applyFog = this.applyFog;
  27845. // Action Manager
  27846. if (this.actionManager) {
  27847. serializationObject.actions = this.actionManager.serialize(this.name);
  27848. }
  27849. };
  27850. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27851. if (!this.geometry) {
  27852. return;
  27853. }
  27854. this._markSubMeshesAsAttributesDirty();
  27855. var morphTargetManager = this._morphTargetManager;
  27856. if (morphTargetManager && morphTargetManager.vertexCount) {
  27857. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27858. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27859. this.morphTargetManager = null;
  27860. return;
  27861. }
  27862. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27863. var morphTarget = morphTargetManager.getActiveTarget(index);
  27864. var positions = morphTarget.getPositions();
  27865. if (!positions) {
  27866. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27867. return;
  27868. }
  27869. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27870. var normals = morphTarget.getNormals();
  27871. if (normals) {
  27872. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27873. }
  27874. var tangents = morphTarget.getTangents();
  27875. if (tangents) {
  27876. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27877. }
  27878. }
  27879. }
  27880. else {
  27881. var index = 0;
  27882. // Positions
  27883. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27884. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27885. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27886. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27887. }
  27888. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27889. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27890. }
  27891. index++;
  27892. }
  27893. }
  27894. };
  27895. // Statics
  27896. /**
  27897. * Returns a new Mesh object parsed from the source provided.
  27898. * The parameter `parsedMesh` is the source.
  27899. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27900. */
  27901. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27902. var mesh;
  27903. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27904. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27905. }
  27906. else {
  27907. mesh = new Mesh(parsedMesh.name, scene);
  27908. }
  27909. mesh.id = parsedMesh.id;
  27910. if (BABYLON.Tags) {
  27911. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27912. }
  27913. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27914. if (parsedMesh.metadata !== undefined) {
  27915. mesh.metadata = parsedMesh.metadata;
  27916. }
  27917. if (parsedMesh.rotationQuaternion) {
  27918. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27919. }
  27920. else if (parsedMesh.rotation) {
  27921. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27922. }
  27923. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27924. if (parsedMesh.localMatrix) {
  27925. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27926. }
  27927. else if (parsedMesh.pivotMatrix) {
  27928. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27929. }
  27930. mesh.setEnabled(parsedMesh.isEnabled);
  27931. mesh.isVisible = parsedMesh.isVisible;
  27932. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27933. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27934. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27935. if (parsedMesh.applyFog !== undefined) {
  27936. mesh.applyFog = parsedMesh.applyFog;
  27937. }
  27938. if (parsedMesh.pickable !== undefined) {
  27939. mesh.isPickable = parsedMesh.pickable;
  27940. }
  27941. if (parsedMesh.alphaIndex !== undefined) {
  27942. mesh.alphaIndex = parsedMesh.alphaIndex;
  27943. }
  27944. mesh.receiveShadows = parsedMesh.receiveShadows;
  27945. mesh.billboardMode = parsedMesh.billboardMode;
  27946. if (parsedMesh.visibility !== undefined) {
  27947. mesh.visibility = parsedMesh.visibility;
  27948. }
  27949. mesh.checkCollisions = parsedMesh.checkCollisions;
  27950. if (parsedMesh.isBlocker !== undefined) {
  27951. mesh.isBlocker = parsedMesh.isBlocker;
  27952. }
  27953. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27954. // freezeWorldMatrix
  27955. if (parsedMesh.freezeWorldMatrix) {
  27956. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27957. }
  27958. // Parent
  27959. if (parsedMesh.parentId) {
  27960. mesh._waitingParentId = parsedMesh.parentId;
  27961. }
  27962. // Actions
  27963. if (parsedMesh.actions !== undefined) {
  27964. mesh._waitingActions = parsedMesh.actions;
  27965. }
  27966. // Overlay
  27967. if (parsedMesh.overlayAlpha !== undefined) {
  27968. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27969. }
  27970. if (parsedMesh.overlayColor !== undefined) {
  27971. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27972. }
  27973. if (parsedMesh.renderOverlay !== undefined) {
  27974. mesh.renderOverlay = parsedMesh.renderOverlay;
  27975. }
  27976. // Geometry
  27977. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27978. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27979. if (parsedMesh.delayLoadingFile) {
  27980. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27981. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27982. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27983. if (parsedMesh._binaryInfo) {
  27984. mesh._binaryInfo = parsedMesh._binaryInfo;
  27985. }
  27986. mesh._delayInfo = [];
  27987. if (parsedMesh.hasUVs) {
  27988. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27989. }
  27990. if (parsedMesh.hasUVs2) {
  27991. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27992. }
  27993. if (parsedMesh.hasUVs3) {
  27994. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27995. }
  27996. if (parsedMesh.hasUVs4) {
  27997. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27998. }
  27999. if (parsedMesh.hasUVs5) {
  28000. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28001. }
  28002. if (parsedMesh.hasUVs6) {
  28003. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28004. }
  28005. if (parsedMesh.hasColors) {
  28006. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28007. }
  28008. if (parsedMesh.hasMatricesIndices) {
  28009. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28010. }
  28011. if (parsedMesh.hasMatricesWeights) {
  28012. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28013. }
  28014. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28015. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28016. mesh._checkDelayState();
  28017. }
  28018. }
  28019. else {
  28020. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  28021. }
  28022. // Material
  28023. if (parsedMesh.materialId) {
  28024. mesh.setMaterialByID(parsedMesh.materialId);
  28025. }
  28026. else {
  28027. mesh.material = null;
  28028. }
  28029. // Morph targets
  28030. if (parsedMesh.morphTargetManagerId > -1) {
  28031. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  28032. }
  28033. // Skeleton
  28034. if (parsedMesh.skeletonId > -1) {
  28035. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  28036. if (parsedMesh.numBoneInfluencers) {
  28037. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  28038. }
  28039. }
  28040. // Animations
  28041. if (parsedMesh.animations) {
  28042. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28043. var parsedAnimation = parsedMesh.animations[animationIndex];
  28044. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28045. }
  28046. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  28047. }
  28048. if (parsedMesh.autoAnimate) {
  28049. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  28050. }
  28051. // Layer Mask
  28052. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  28053. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  28054. }
  28055. else {
  28056. mesh.layerMask = 0x0FFFFFFF;
  28057. }
  28058. // Physics
  28059. if (parsedMesh.physicsImpostor) {
  28060. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  28061. mass: parsedMesh.physicsMass,
  28062. friction: parsedMesh.physicsFriction,
  28063. restitution: parsedMesh.physicsRestitution
  28064. }, scene);
  28065. }
  28066. // Instances
  28067. if (parsedMesh.instances) {
  28068. for (var index = 0; index < parsedMesh.instances.length; index++) {
  28069. var parsedInstance = parsedMesh.instances[index];
  28070. var instance = mesh.createInstance(parsedInstance.name);
  28071. if (parsedInstance.id) {
  28072. instance.id = parsedInstance.id;
  28073. }
  28074. if (BABYLON.Tags) {
  28075. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  28076. }
  28077. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  28078. if (parsedInstance.parentId) {
  28079. instance._waitingParentId = parsedInstance.parentId;
  28080. }
  28081. if (parsedInstance.rotationQuaternion) {
  28082. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  28083. }
  28084. else if (parsedInstance.rotation) {
  28085. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  28086. }
  28087. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  28088. instance.checkCollisions = mesh.checkCollisions;
  28089. if (parsedMesh.animations) {
  28090. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28091. parsedAnimation = parsedMesh.animations[animationIndex];
  28092. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28093. }
  28094. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  28095. }
  28096. }
  28097. }
  28098. return mesh;
  28099. };
  28100. /**
  28101. * Creates a ribbon mesh.
  28102. * Please consider using the same method from the MeshBuilder class instead.
  28103. * 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.
  28104. *
  28105. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28106. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28107. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28108. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28109. * 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.
  28110. * 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.
  28111. * 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
  28112. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28113. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28115. */
  28116. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28117. if (closeArray === void 0) { closeArray = false; }
  28118. if (updatable === void 0) { updatable = false; }
  28119. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28120. pathArray: pathArray,
  28121. closeArray: closeArray,
  28122. closePath: closePath,
  28123. offset: offset,
  28124. updatable: updatable,
  28125. sideOrientation: sideOrientation,
  28126. instance: instance
  28127. }, scene);
  28128. };
  28129. /**
  28130. * Creates a plane polygonal mesh. By default, this is a disc.
  28131. * Please consider using the same method from the MeshBuilder class instead.
  28132. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28133. * 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.
  28134. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28135. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28136. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28137. */
  28138. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28139. if (scene === void 0) { scene = null; }
  28140. var options = {
  28141. radius: radius,
  28142. tessellation: tessellation,
  28143. sideOrientation: sideOrientation,
  28144. updatable: updatable
  28145. };
  28146. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28147. };
  28148. /**
  28149. * Creates a box mesh.
  28150. * Please consider using the same method from the MeshBuilder class instead.
  28151. * The parameter `size` sets the size (float) of each box side (default 1).
  28152. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28153. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28154. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28155. */
  28156. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28157. if (scene === void 0) { scene = null; }
  28158. var options = {
  28159. size: size,
  28160. sideOrientation: sideOrientation,
  28161. updatable: updatable
  28162. };
  28163. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28164. };
  28165. /**
  28166. * Creates a sphere mesh.
  28167. * Please consider using the same method from the MeshBuilder class instead.
  28168. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28169. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28171. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28173. */
  28174. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28175. var options = {
  28176. segments: segments,
  28177. diameterX: diameter,
  28178. diameterY: diameter,
  28179. diameterZ: diameter,
  28180. sideOrientation: sideOrientation,
  28181. updatable: updatable
  28182. };
  28183. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  28184. };
  28185. /**
  28186. * Creates a cylinder or a cone mesh.
  28187. * Please consider using the same method from the MeshBuilder class instead.
  28188. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28189. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28190. * 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.
  28191. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28192. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28193. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28194. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28196. */
  28197. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  28198. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  28199. if (scene !== undefined) {
  28200. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  28201. updatable = scene;
  28202. }
  28203. scene = subdivisions;
  28204. subdivisions = 1;
  28205. }
  28206. var options = {
  28207. height: height,
  28208. diameterTop: diameterTop,
  28209. diameterBottom: diameterBottom,
  28210. tessellation: tessellation,
  28211. subdivisions: subdivisions,
  28212. sideOrientation: sideOrientation,
  28213. updatable: updatable
  28214. };
  28215. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  28216. };
  28217. // Torus (Code from SharpDX.org)
  28218. /**
  28219. * Creates a torus mesh.
  28220. * Please consider using the same method from the MeshBuilder class instead.
  28221. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28222. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28223. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28224. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28225. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28227. */
  28228. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  28229. var options = {
  28230. diameter: diameter,
  28231. thickness: thickness,
  28232. tessellation: tessellation,
  28233. sideOrientation: sideOrientation,
  28234. updatable: updatable
  28235. };
  28236. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  28237. };
  28238. /**
  28239. * Creates a torus knot mesh.
  28240. * Please consider using the same method from the MeshBuilder class instead.
  28241. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28242. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28243. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28244. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28245. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28246. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28247. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28248. */
  28249. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  28250. var options = {
  28251. radius: radius,
  28252. tube: tube,
  28253. radialSegments: radialSegments,
  28254. tubularSegments: tubularSegments,
  28255. p: p,
  28256. q: q,
  28257. sideOrientation: sideOrientation,
  28258. updatable: updatable
  28259. };
  28260. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28261. };
  28262. /**
  28263. * Creates a line mesh.
  28264. * Please consider using the same method from the MeshBuilder class instead.
  28265. * 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.
  28266. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28267. * The parameter `points` is an array successive Vector3.
  28268. * 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
  28269. * When updating an instance, remember that only point positions can change, not the number of points.
  28270. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28271. */
  28272. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28273. if (scene === void 0) { scene = null; }
  28274. if (updatable === void 0) { updatable = false; }
  28275. if (instance === void 0) { instance = null; }
  28276. var options = {
  28277. points: points,
  28278. updatable: updatable,
  28279. instance: instance
  28280. };
  28281. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28282. };
  28283. /**
  28284. * Creates a dashed line mesh.
  28285. * Please consider using the same method from the MeshBuilder class instead.
  28286. * 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.
  28287. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28288. * The parameter `points` is an array successive Vector3.
  28289. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28290. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28291. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28292. * 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
  28293. * When updating an instance, remember that only point positions can change, not the number of points.
  28294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28295. */
  28296. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  28297. if (scene === void 0) { scene = null; }
  28298. var options = {
  28299. points: points,
  28300. dashSize: dashSize,
  28301. gapSize: gapSize,
  28302. dashNb: dashNb,
  28303. updatable: updatable,
  28304. instance: instance
  28305. };
  28306. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  28307. };
  28308. /**
  28309. * Creates a polygon mesh.
  28310. * Please consider using the same method from the MeshBuilder class instead.
  28311. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  28312. * 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.
  28313. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28315. * Remember you can only change the shape positions, not their number when updating a polygon.
  28316. */
  28317. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  28318. var options = {
  28319. shape: shape,
  28320. holes: holes,
  28321. updatable: updatable,
  28322. sideOrientation: sideOrientation
  28323. };
  28324. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  28325. };
  28326. /**
  28327. * Creates an extruded polygon mesh, with depth in the Y direction.
  28328. * Please consider using the same method from the MeshBuilder class instead.
  28329. */
  28330. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  28331. var options = {
  28332. shape: shape,
  28333. holes: holes,
  28334. depth: depth,
  28335. updatable: updatable,
  28336. sideOrientation: sideOrientation
  28337. };
  28338. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  28339. };
  28340. /**
  28341. * Creates an extruded shape mesh.
  28342. * 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.
  28343. * Please consider using the same method from the MeshBuilder class instead.
  28344. *
  28345. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28346. * 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
  28347. * extruded along the Z axis.
  28348. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28349. * 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.
  28350. * The parameter `scale` (float, default 1) is the value to scale the shape.
  28351. * 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
  28352. * 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
  28353. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28354. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28355. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28356. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28357. */
  28358. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  28359. if (scene === void 0) { scene = null; }
  28360. var options = {
  28361. shape: shape,
  28362. path: path,
  28363. scale: scale,
  28364. rotation: rotation,
  28365. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28366. sideOrientation: sideOrientation,
  28367. instance: instance,
  28368. updatable: updatable
  28369. };
  28370. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  28371. };
  28372. /**
  28373. * Creates an custom extruded shape mesh.
  28374. * 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.
  28375. * Please consider using the same method from the MeshBuilder class instead.
  28376. *
  28377. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28378. * 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
  28379. * extruded along the Z axis.
  28380. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28381. * 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
  28382. * and the distance of this point from the begining of the path :
  28383. * ```javascript
  28384. * var rotationFunction = function(i, distance) {
  28385. * // do things
  28386. * return rotationValue; }
  28387. * ```
  28388. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  28389. * 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
  28390. * and the distance of this point from the begining of the path :
  28391. * ```javascript
  28392. * var scaleFunction = function(i, distance) {
  28393. * // do things
  28394. * return scaleValue;}
  28395. * ```
  28396. * It must returns a float value that will be the scale value applied to the shape on each path point.
  28397. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  28398. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  28399. * 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
  28400. * 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
  28401. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28402. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28403. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28405. */
  28406. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  28407. var options = {
  28408. shape: shape,
  28409. path: path,
  28410. scaleFunction: scaleFunction,
  28411. rotationFunction: rotationFunction,
  28412. ribbonCloseArray: ribbonCloseArray,
  28413. ribbonClosePath: ribbonClosePath,
  28414. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28415. sideOrientation: sideOrientation,
  28416. instance: instance,
  28417. updatable: updatable
  28418. };
  28419. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  28420. };
  28421. /**
  28422. * Creates lathe mesh.
  28423. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  28424. * Please consider using the same method from the MeshBuilder class instead.
  28425. * 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
  28426. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  28427. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  28428. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  28429. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28430. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28432. */
  28433. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  28434. var options = {
  28435. shape: shape,
  28436. radius: radius,
  28437. tessellation: tessellation,
  28438. sideOrientation: sideOrientation,
  28439. updatable: updatable
  28440. };
  28441. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  28442. };
  28443. /**
  28444. * Creates a plane mesh.
  28445. * Please consider using the same method from the MeshBuilder class instead.
  28446. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  28447. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28448. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28450. */
  28451. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  28452. var options = {
  28453. size: size,
  28454. width: size,
  28455. height: size,
  28456. sideOrientation: sideOrientation,
  28457. updatable: updatable
  28458. };
  28459. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  28460. };
  28461. /**
  28462. * Creates a ground mesh.
  28463. * Please consider using the same method from the MeshBuilder class instead.
  28464. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  28465. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  28466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28467. */
  28468. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  28469. var options = {
  28470. width: width,
  28471. height: height,
  28472. subdivisions: subdivisions,
  28473. updatable: updatable
  28474. };
  28475. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  28476. };
  28477. /**
  28478. * Creates a tiled ground mesh.
  28479. * Please consider using the same method from the MeshBuilder class instead.
  28480. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  28481. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  28482. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  28483. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  28484. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  28485. * numbers of subdivisions on the ground width and height of each tile.
  28486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28487. */
  28488. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  28489. var options = {
  28490. xmin: xmin,
  28491. zmin: zmin,
  28492. xmax: xmax,
  28493. zmax: zmax,
  28494. subdivisions: subdivisions,
  28495. precision: precision,
  28496. updatable: updatable
  28497. };
  28498. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  28499. };
  28500. /**
  28501. * Creates a ground mesh from a height map.
  28502. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  28503. * Please consider using the same method from the MeshBuilder class instead.
  28504. * The parameter `url` sets the URL of the height map image resource.
  28505. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  28506. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  28507. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  28508. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  28509. * 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).
  28510. * This function is passed the newly built mesh :
  28511. * ```javascript
  28512. * function(mesh) { // do things
  28513. * return; }
  28514. * ```
  28515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28516. */
  28517. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  28518. var options = {
  28519. width: width,
  28520. height: height,
  28521. subdivisions: subdivisions,
  28522. minHeight: minHeight,
  28523. maxHeight: maxHeight,
  28524. updatable: updatable,
  28525. onReady: onReady
  28526. };
  28527. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  28528. };
  28529. /**
  28530. * Creates a tube mesh.
  28531. * 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.
  28532. * Please consider using the same method from the MeshBuilder class instead.
  28533. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  28534. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  28535. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  28536. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  28537. * 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.
  28538. * It must return a radius value (positive float) :
  28539. * ```javascript
  28540. * var radiusFunction = function(i, distance) {
  28541. * // do things
  28542. * return radius; }
  28543. * ```
  28544. * 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
  28545. * 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
  28546. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28547. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28548. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28549. */
  28550. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  28551. var options = {
  28552. path: path,
  28553. radius: radius,
  28554. tessellation: tessellation,
  28555. radiusFunction: radiusFunction,
  28556. arc: 1,
  28557. cap: cap,
  28558. updatable: updatable,
  28559. sideOrientation: sideOrientation,
  28560. instance: instance
  28561. };
  28562. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  28563. };
  28564. /**
  28565. * Creates a polyhedron mesh.
  28566. * Please consider using the same method from the MeshBuilder class instead.
  28567. * 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
  28568. * to choose the wanted type.
  28569. * The parameter `size` (positive float, default 1) sets the polygon size.
  28570. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  28571. * 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`.
  28572. * 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
  28573. * 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)`).
  28574. * 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
  28575. * 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.
  28576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28579. */
  28580. Mesh.CreatePolyhedron = function (name, options, scene) {
  28581. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  28582. };
  28583. /**
  28584. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28585. * Please consider using the same method from the MeshBuilder class instead.
  28586. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28587. * 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`).
  28588. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28589. * 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.
  28590. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28591. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28592. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28593. */
  28594. Mesh.CreateIcoSphere = function (name, options, scene) {
  28595. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  28596. };
  28597. /**
  28598. * Creates a decal mesh.
  28599. * Please consider using the same method from the MeshBuilder class instead.
  28600. * 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.
  28601. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  28602. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  28603. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  28604. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  28605. */
  28606. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  28607. var options = {
  28608. position: position,
  28609. normal: normal,
  28610. size: size,
  28611. angle: angle
  28612. };
  28613. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  28614. };
  28615. // Skeletons
  28616. /**
  28617. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28618. */
  28619. Mesh.prototype.setPositionsForCPUSkinning = function () {
  28620. if (!this._sourcePositions) {
  28621. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28622. if (!source) {
  28623. return this._sourcePositions;
  28624. }
  28625. this._sourcePositions = new Float32Array(source);
  28626. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  28627. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  28628. }
  28629. }
  28630. return this._sourcePositions;
  28631. };
  28632. /**
  28633. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28634. */
  28635. Mesh.prototype.setNormalsForCPUSkinning = function () {
  28636. if (!this._sourceNormals) {
  28637. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28638. if (!source) {
  28639. return this._sourceNormals;
  28640. }
  28641. this._sourceNormals = new Float32Array(source);
  28642. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  28643. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  28644. }
  28645. }
  28646. return this._sourceNormals;
  28647. };
  28648. /**
  28649. * Updates the vertex buffer by applying transformation from the bones.
  28650. * Returns the Mesh.
  28651. *
  28652. * @param {skeleton} skeleton to apply
  28653. */
  28654. Mesh.prototype.applySkeleton = function (skeleton) {
  28655. if (!this.geometry) {
  28656. return this;
  28657. }
  28658. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  28659. return this;
  28660. }
  28661. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  28662. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28663. return this;
  28664. }
  28665. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28666. return this;
  28667. }
  28668. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28669. return this;
  28670. }
  28671. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28672. return this;
  28673. }
  28674. if (!this._sourcePositions) {
  28675. var submeshes = this.subMeshes.slice();
  28676. this.setPositionsForCPUSkinning();
  28677. this.subMeshes = submeshes;
  28678. }
  28679. if (!this._sourceNormals) {
  28680. this.setNormalsForCPUSkinning();
  28681. }
  28682. // positionsData checks for not being Float32Array will only pass at most once
  28683. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28684. if (!positionsData) {
  28685. return this;
  28686. }
  28687. if (!(positionsData instanceof Float32Array)) {
  28688. positionsData = new Float32Array(positionsData);
  28689. }
  28690. // normalsData checks for not being Float32Array will only pass at most once
  28691. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28692. if (!normalsData) {
  28693. return this;
  28694. }
  28695. if (!(normalsData instanceof Float32Array)) {
  28696. normalsData = new Float32Array(normalsData);
  28697. }
  28698. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28699. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28700. if (!matricesWeightsData || !matricesIndicesData) {
  28701. return this;
  28702. }
  28703. var needExtras = this.numBoneInfluencers > 4;
  28704. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28705. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28706. var skeletonMatrices = skeleton.getTransformMatrices(this);
  28707. var tempVector3 = BABYLON.Vector3.Zero();
  28708. var finalMatrix = new BABYLON.Matrix();
  28709. var tempMatrix = new BABYLON.Matrix();
  28710. var matWeightIdx = 0;
  28711. var inf;
  28712. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  28713. var weight;
  28714. for (inf = 0; inf < 4; inf++) {
  28715. weight = matricesWeightsData[matWeightIdx + inf];
  28716. if (weight > 0) {
  28717. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28718. finalMatrix.addToSelf(tempMatrix);
  28719. }
  28720. else
  28721. break;
  28722. }
  28723. if (needExtras) {
  28724. for (inf = 0; inf < 4; inf++) {
  28725. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28726. if (weight > 0) {
  28727. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28728. finalMatrix.addToSelf(tempMatrix);
  28729. }
  28730. else
  28731. break;
  28732. }
  28733. }
  28734. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  28735. tempVector3.toArray(positionsData, index);
  28736. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  28737. tempVector3.toArray(normalsData, index);
  28738. finalMatrix.reset();
  28739. }
  28740. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  28741. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  28742. return this;
  28743. };
  28744. // Tools
  28745. /**
  28746. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  28747. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  28748. */
  28749. Mesh.MinMax = function (meshes) {
  28750. var minVector = null;
  28751. var maxVector = null;
  28752. meshes.forEach(function (mesh, index, array) {
  28753. var boundingInfo = mesh.getBoundingInfo();
  28754. var boundingBox = boundingInfo.boundingBox;
  28755. if (!minVector || !maxVector) {
  28756. minVector = boundingBox.minimumWorld;
  28757. maxVector = boundingBox.maximumWorld;
  28758. }
  28759. else {
  28760. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28761. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28762. }
  28763. });
  28764. if (!minVector || !maxVector) {
  28765. return {
  28766. min: BABYLON.Vector3.Zero(),
  28767. max: BABYLON.Vector3.Zero()
  28768. };
  28769. }
  28770. return {
  28771. min: minVector,
  28772. max: maxVector
  28773. };
  28774. };
  28775. /**
  28776. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28777. */
  28778. Mesh.Center = function (meshesOrMinMaxVector) {
  28779. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28780. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28781. };
  28782. /**
  28783. * Merge the array of meshes into a single mesh for performance reasons.
  28784. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28785. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28786. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28787. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28788. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28789. */
  28790. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28791. if (disposeSource === void 0) { disposeSource = true; }
  28792. var index;
  28793. if (!allow32BitsIndices) {
  28794. var totalVertices = 0;
  28795. // Counting vertices
  28796. for (index = 0; index < meshes.length; index++) {
  28797. if (meshes[index]) {
  28798. totalVertices += meshes[index].getTotalVertices();
  28799. if (totalVertices > 65536) {
  28800. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28801. return null;
  28802. }
  28803. }
  28804. }
  28805. }
  28806. // Merge
  28807. var vertexData = null;
  28808. var otherVertexData;
  28809. var indiceArray = new Array();
  28810. var source = null;
  28811. for (index = 0; index < meshes.length; index++) {
  28812. if (meshes[index]) {
  28813. meshes[index].computeWorldMatrix(true);
  28814. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28815. otherVertexData.transform(meshes[index].getWorldMatrix());
  28816. if (vertexData) {
  28817. vertexData.merge(otherVertexData);
  28818. }
  28819. else {
  28820. vertexData = otherVertexData;
  28821. source = meshes[index];
  28822. }
  28823. if (subdivideWithSubMeshes) {
  28824. indiceArray.push(meshes[index].getTotalIndices());
  28825. }
  28826. }
  28827. }
  28828. source = source;
  28829. if (!meshSubclass) {
  28830. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28831. }
  28832. vertexData.applyToMesh(meshSubclass);
  28833. // Setting properties
  28834. meshSubclass.material = source.material;
  28835. meshSubclass.checkCollisions = source.checkCollisions;
  28836. // Cleaning
  28837. if (disposeSource) {
  28838. for (index = 0; index < meshes.length; index++) {
  28839. if (meshes[index]) {
  28840. meshes[index].dispose();
  28841. }
  28842. }
  28843. }
  28844. // Subdivide
  28845. if (subdivideWithSubMeshes) {
  28846. //-- Suppresions du submesh global
  28847. meshSubclass.releaseSubMeshes();
  28848. index = 0;
  28849. var offset = 0;
  28850. //-- aplique la subdivision en fonction du tableau d'indices
  28851. while (index < indiceArray.length) {
  28852. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28853. offset += indiceArray[index];
  28854. index++;
  28855. }
  28856. }
  28857. return meshSubclass;
  28858. };
  28859. // Consts
  28860. Mesh._FRONTSIDE = 0;
  28861. Mesh._BACKSIDE = 1;
  28862. Mesh._DOUBLESIDE = 2;
  28863. Mesh._DEFAULTSIDE = 0;
  28864. Mesh._NO_CAP = 0;
  28865. Mesh._CAP_START = 1;
  28866. Mesh._CAP_END = 2;
  28867. Mesh._CAP_ALL = 3;
  28868. return Mesh;
  28869. }(BABYLON.AbstractMesh));
  28870. BABYLON.Mesh = Mesh;
  28871. })(BABYLON || (BABYLON = {}));
  28872. //# sourceMappingURL=babylon.mesh.js.map
  28873. var BABYLON;
  28874. (function (BABYLON) {
  28875. var BaseSubMesh = /** @class */ (function () {
  28876. function BaseSubMesh() {
  28877. }
  28878. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28879. get: function () {
  28880. return this._materialEffect;
  28881. },
  28882. enumerable: true,
  28883. configurable: true
  28884. });
  28885. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28886. if (defines === void 0) { defines = null; }
  28887. if (this._materialEffect === effect) {
  28888. if (!effect) {
  28889. this._materialDefines = null;
  28890. }
  28891. return;
  28892. }
  28893. this._materialDefines = defines;
  28894. this._materialEffect = effect;
  28895. };
  28896. return BaseSubMesh;
  28897. }());
  28898. BABYLON.BaseSubMesh = BaseSubMesh;
  28899. var SubMesh = /** @class */ (function (_super) {
  28900. __extends(SubMesh, _super);
  28901. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28902. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28903. var _this = _super.call(this) || this;
  28904. _this.materialIndex = materialIndex;
  28905. _this.verticesStart = verticesStart;
  28906. _this.verticesCount = verticesCount;
  28907. _this.indexStart = indexStart;
  28908. _this.indexCount = indexCount;
  28909. _this._renderId = 0;
  28910. _this._mesh = mesh;
  28911. _this._renderingMesh = renderingMesh || mesh;
  28912. mesh.subMeshes.push(_this);
  28913. _this._trianglePlanes = [];
  28914. _this._id = mesh.subMeshes.length - 1;
  28915. if (createBoundingBox) {
  28916. _this.refreshBoundingInfo();
  28917. mesh.computeWorldMatrix(true);
  28918. }
  28919. return _this;
  28920. }
  28921. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28922. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28923. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28924. };
  28925. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28926. get: function () {
  28927. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28928. },
  28929. enumerable: true,
  28930. configurable: true
  28931. });
  28932. /**
  28933. * Returns the submesh BoudingInfo object.
  28934. */
  28935. SubMesh.prototype.getBoundingInfo = function () {
  28936. if (this.IsGlobal) {
  28937. return this._mesh.getBoundingInfo();
  28938. }
  28939. return this._boundingInfo;
  28940. };
  28941. /**
  28942. * Sets the submesh BoundingInfo.
  28943. * Return the SubMesh.
  28944. */
  28945. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28946. this._boundingInfo = boundingInfo;
  28947. return this;
  28948. };
  28949. /**
  28950. * Returns the mesh of the current submesh.
  28951. */
  28952. SubMesh.prototype.getMesh = function () {
  28953. return this._mesh;
  28954. };
  28955. /**
  28956. * Returns the rendering mesh of the submesh.
  28957. */
  28958. SubMesh.prototype.getRenderingMesh = function () {
  28959. return this._renderingMesh;
  28960. };
  28961. /**
  28962. * Returns the submesh material.
  28963. */
  28964. SubMesh.prototype.getMaterial = function () {
  28965. var rootMaterial = this._renderingMesh.material;
  28966. if (rootMaterial === null || rootMaterial === undefined) {
  28967. return this._mesh.getScene().defaultMaterial;
  28968. }
  28969. else if (rootMaterial.getSubMaterial) {
  28970. var multiMaterial = rootMaterial;
  28971. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28972. if (this._currentMaterial !== effectiveMaterial) {
  28973. this._currentMaterial = effectiveMaterial;
  28974. this._materialDefines = null;
  28975. }
  28976. return effectiveMaterial;
  28977. }
  28978. return rootMaterial;
  28979. };
  28980. // Methods
  28981. /**
  28982. * Sets a new updated BoundingInfo object to the submesh.
  28983. * Returns the SubMesh.
  28984. */
  28985. SubMesh.prototype.refreshBoundingInfo = function () {
  28986. this._lastColliderWorldVertices = null;
  28987. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28988. return this;
  28989. }
  28990. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28991. if (!data) {
  28992. this._boundingInfo = this._mesh.getBoundingInfo();
  28993. return this;
  28994. }
  28995. var indices = this._renderingMesh.getIndices();
  28996. var extend;
  28997. //is this the only submesh?
  28998. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28999. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29000. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29001. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29002. }
  29003. else {
  29004. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29005. }
  29006. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29007. return this;
  29008. };
  29009. SubMesh.prototype._checkCollision = function (collider) {
  29010. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29011. return boundingInfo._checkCollision(collider);
  29012. };
  29013. /**
  29014. * Updates the submesh BoundingInfo.
  29015. * Returns the Submesh.
  29016. */
  29017. SubMesh.prototype.updateBoundingInfo = function (world) {
  29018. var boundingInfo = this.getBoundingInfo();
  29019. if (!boundingInfo) {
  29020. this.refreshBoundingInfo();
  29021. boundingInfo = this.getBoundingInfo();
  29022. }
  29023. boundingInfo.update(world);
  29024. return this;
  29025. };
  29026. /**
  29027. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  29028. * Boolean returned.
  29029. */
  29030. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  29031. var boundingInfo = this.getBoundingInfo();
  29032. if (!boundingInfo) {
  29033. return false;
  29034. }
  29035. return boundingInfo.isInFrustum(frustumPlanes);
  29036. };
  29037. /**
  29038. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  29039. * Boolean returned.
  29040. */
  29041. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  29042. var boundingInfo = this.getBoundingInfo();
  29043. if (!boundingInfo) {
  29044. return false;
  29045. }
  29046. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  29047. };
  29048. /**
  29049. * Renders the submesh.
  29050. * Returns it.
  29051. */
  29052. SubMesh.prototype.render = function (enableAlphaMode) {
  29053. this._renderingMesh.render(this, enableAlphaMode);
  29054. return this;
  29055. };
  29056. /**
  29057. * Returns a new Index Buffer.
  29058. * Type returned : WebGLBuffer.
  29059. */
  29060. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  29061. if (!this._linesIndexBuffer) {
  29062. var linesIndices = [];
  29063. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29064. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  29065. }
  29066. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  29067. this.linesIndexCount = linesIndices.length;
  29068. }
  29069. return this._linesIndexBuffer;
  29070. };
  29071. /**
  29072. * True is the passed Ray intersects the submesh bounding box.
  29073. * Boolean returned.
  29074. */
  29075. SubMesh.prototype.canIntersects = function (ray) {
  29076. var boundingInfo = this.getBoundingInfo();
  29077. if (!boundingInfo) {
  29078. return false;
  29079. }
  29080. return ray.intersectsBox(boundingInfo.boundingBox);
  29081. };
  29082. /**
  29083. * Returns an object IntersectionInfo.
  29084. */
  29085. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  29086. var intersectInfo = null;
  29087. // LineMesh first as it's also a Mesh...
  29088. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  29089. var lineMesh = this._mesh;
  29090. // Line test
  29091. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  29092. var p0 = positions[indices[index]];
  29093. var p1 = positions[indices[index + 1]];
  29094. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  29095. if (length < 0) {
  29096. continue;
  29097. }
  29098. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  29099. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  29100. if (fastCheck) {
  29101. break;
  29102. }
  29103. }
  29104. }
  29105. }
  29106. else {
  29107. // Triangles test
  29108. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29109. var p0 = positions[indices[index]];
  29110. var p1 = positions[indices[index + 1]];
  29111. var p2 = positions[indices[index + 2]];
  29112. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29113. if (currentIntersectInfo) {
  29114. if (currentIntersectInfo.distance < 0) {
  29115. continue;
  29116. }
  29117. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29118. intersectInfo = currentIntersectInfo;
  29119. intersectInfo.faceId = index / 3;
  29120. if (fastCheck) {
  29121. break;
  29122. }
  29123. }
  29124. }
  29125. }
  29126. }
  29127. return intersectInfo;
  29128. };
  29129. SubMesh.prototype._rebuild = function () {
  29130. if (this._linesIndexBuffer) {
  29131. this._linesIndexBuffer = null;
  29132. }
  29133. };
  29134. // Clone
  29135. /**
  29136. * Creates a new Submesh from the passed Mesh.
  29137. */
  29138. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29139. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29140. if (!this.IsGlobal) {
  29141. var boundingInfo = this.getBoundingInfo();
  29142. if (!boundingInfo) {
  29143. return result;
  29144. }
  29145. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29146. }
  29147. return result;
  29148. };
  29149. // Dispose
  29150. /**
  29151. * Disposes the Submesh.
  29152. * Returns nothing.
  29153. */
  29154. SubMesh.prototype.dispose = function () {
  29155. if (this._linesIndexBuffer) {
  29156. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29157. this._linesIndexBuffer = null;
  29158. }
  29159. // Remove from mesh
  29160. var index = this._mesh.subMeshes.indexOf(this);
  29161. this._mesh.subMeshes.splice(index, 1);
  29162. };
  29163. // Statics
  29164. /**
  29165. * Creates a new Submesh from the passed parameters :
  29166. * - materialIndex (integer) : the index of the main mesh material.
  29167. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29168. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29169. * - mesh (Mesh) : the main mesh to create the submesh from.
  29170. * - renderingMesh (optional Mesh) : rendering mesh.
  29171. */
  29172. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29173. var minVertexIndex = Number.MAX_VALUE;
  29174. var maxVertexIndex = -Number.MAX_VALUE;
  29175. renderingMesh = (renderingMesh || mesh);
  29176. var indices = renderingMesh.getIndices();
  29177. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29178. var vertexIndex = indices[index];
  29179. if (vertexIndex < minVertexIndex)
  29180. minVertexIndex = vertexIndex;
  29181. if (vertexIndex > maxVertexIndex)
  29182. maxVertexIndex = vertexIndex;
  29183. }
  29184. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  29185. };
  29186. return SubMesh;
  29187. }(BaseSubMesh));
  29188. BABYLON.SubMesh = SubMesh;
  29189. })(BABYLON || (BABYLON = {}));
  29190. //# sourceMappingURL=babylon.subMesh.js.map
  29191. var __assign = (this && this.__assign) || Object.assign || function(t) {
  29192. for (var s, i = 1, n = arguments.length; i < n; i++) {
  29193. s = arguments[i];
  29194. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29195. t[p] = s[p];
  29196. }
  29197. return t;
  29198. };
  29199. var BABYLON;
  29200. (function (BABYLON) {
  29201. var MaterialDefines = /** @class */ (function () {
  29202. function MaterialDefines() {
  29203. this._isDirty = true;
  29204. this._areLightsDirty = true;
  29205. this._areAttributesDirty = true;
  29206. this._areTexturesDirty = true;
  29207. this._areFresnelDirty = true;
  29208. this._areMiscDirty = true;
  29209. this._areImageProcessingDirty = true;
  29210. this._normals = false;
  29211. this._uvs = false;
  29212. this._needNormals = false;
  29213. this._needUVs = false;
  29214. }
  29215. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  29216. get: function () {
  29217. return this._isDirty;
  29218. },
  29219. enumerable: true,
  29220. configurable: true
  29221. });
  29222. MaterialDefines.prototype.markAsProcessed = function () {
  29223. this._isDirty = false;
  29224. this._areAttributesDirty = false;
  29225. this._areTexturesDirty = false;
  29226. this._areFresnelDirty = false;
  29227. this._areLightsDirty = false;
  29228. this._areMiscDirty = false;
  29229. this._areImageProcessingDirty = false;
  29230. };
  29231. MaterialDefines.prototype.markAsUnprocessed = function () {
  29232. this._isDirty = true;
  29233. };
  29234. MaterialDefines.prototype.markAllAsDirty = function () {
  29235. this._areTexturesDirty = true;
  29236. this._areAttributesDirty = true;
  29237. this._areLightsDirty = true;
  29238. this._areFresnelDirty = true;
  29239. this._areMiscDirty = true;
  29240. this._areImageProcessingDirty = true;
  29241. this._isDirty = true;
  29242. };
  29243. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  29244. this._areImageProcessingDirty = true;
  29245. this._isDirty = true;
  29246. };
  29247. MaterialDefines.prototype.markAsLightDirty = function () {
  29248. this._areLightsDirty = true;
  29249. this._isDirty = true;
  29250. };
  29251. MaterialDefines.prototype.markAsAttributesDirty = function () {
  29252. this._areAttributesDirty = true;
  29253. this._isDirty = true;
  29254. };
  29255. MaterialDefines.prototype.markAsTexturesDirty = function () {
  29256. this._areTexturesDirty = true;
  29257. this._isDirty = true;
  29258. };
  29259. MaterialDefines.prototype.markAsFresnelDirty = function () {
  29260. this._areFresnelDirty = true;
  29261. this._isDirty = true;
  29262. };
  29263. MaterialDefines.prototype.markAsMiscDirty = function () {
  29264. this._areMiscDirty = true;
  29265. this._isDirty = true;
  29266. };
  29267. MaterialDefines.prototype.rebuild = function () {
  29268. if (this._keys) {
  29269. delete this._keys;
  29270. }
  29271. this._keys = [];
  29272. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  29273. var key = _a[_i];
  29274. if (key[0] === "_") {
  29275. continue;
  29276. }
  29277. this._keys.push(key);
  29278. }
  29279. };
  29280. MaterialDefines.prototype.isEqual = function (other) {
  29281. if (this._keys.length !== other._keys.length) {
  29282. return false;
  29283. }
  29284. for (var index = 0; index < this._keys.length; index++) {
  29285. var prop = this._keys[index];
  29286. if (this[prop] !== other[prop]) {
  29287. return false;
  29288. }
  29289. }
  29290. return true;
  29291. };
  29292. MaterialDefines.prototype.cloneTo = function (other) {
  29293. if (this._keys.length !== other._keys.length) {
  29294. other._keys = this._keys.slice(0);
  29295. }
  29296. for (var index = 0; index < this._keys.length; index++) {
  29297. var prop = this._keys[index];
  29298. other[prop] = this[prop];
  29299. }
  29300. };
  29301. MaterialDefines.prototype.reset = function () {
  29302. for (var index = 0; index < this._keys.length; index++) {
  29303. var prop = this._keys[index];
  29304. if (typeof (this[prop]) === "number") {
  29305. this[prop] = 0;
  29306. }
  29307. else {
  29308. this[prop] = false;
  29309. }
  29310. }
  29311. };
  29312. MaterialDefines.prototype.toString = function () {
  29313. var result = "";
  29314. for (var index = 0; index < this._keys.length; index++) {
  29315. var prop = this._keys[index];
  29316. var value = this[prop];
  29317. if (typeof (value) === "number") {
  29318. result += "#define " + prop + " " + this[prop] + "\n";
  29319. }
  29320. else if (value) {
  29321. result += "#define " + prop + "\n";
  29322. }
  29323. }
  29324. return result;
  29325. };
  29326. return MaterialDefines;
  29327. }());
  29328. BABYLON.MaterialDefines = MaterialDefines;
  29329. var Material = /** @class */ (function () {
  29330. function Material(name, scene, doNotAdd) {
  29331. this.checkReadyOnEveryCall = false;
  29332. this.checkReadyOnlyOnce = false;
  29333. this.state = "";
  29334. this._alpha = 1.0;
  29335. this._backFaceCulling = true;
  29336. this.doNotSerialize = false;
  29337. this.storeEffectOnSubMeshes = false;
  29338. /**
  29339. * An event triggered when the material is disposed.
  29340. * @type {BABYLON.Observable}
  29341. */
  29342. this.onDisposeObservable = new BABYLON.Observable();
  29343. /**
  29344. * An event triggered when the material is bound.
  29345. * @type {BABYLON.Observable}
  29346. */
  29347. this.onBindObservable = new BABYLON.Observable();
  29348. /**
  29349. * An event triggered when the material is unbound.
  29350. * @type {BABYLON.Observable}
  29351. */
  29352. this.onUnBindObservable = new BABYLON.Observable();
  29353. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29354. this._needDepthPrePass = false;
  29355. this.disableDepthWrite = false;
  29356. this.forceDepthWrite = false;
  29357. this.separateCullingPass = false;
  29358. this._fogEnabled = true;
  29359. this.pointSize = 1.0;
  29360. this.zOffset = 0;
  29361. this._wasPreviouslyReady = false;
  29362. this._fillMode = Material.TriangleFillMode;
  29363. this.name = name;
  29364. this.id = name || BABYLON.Tools.RandomId();
  29365. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29366. if (this._scene.useRightHandedSystem) {
  29367. this.sideOrientation = Material.ClockWiseSideOrientation;
  29368. }
  29369. else {
  29370. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29371. }
  29372. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  29373. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  29374. if (!doNotAdd) {
  29375. this._scene.materials.push(this);
  29376. }
  29377. }
  29378. Object.defineProperty(Material, "TriangleFillMode", {
  29379. get: function () {
  29380. return Material._TriangleFillMode;
  29381. },
  29382. enumerable: true,
  29383. configurable: true
  29384. });
  29385. Object.defineProperty(Material, "WireFrameFillMode", {
  29386. get: function () {
  29387. return Material._WireFrameFillMode;
  29388. },
  29389. enumerable: true,
  29390. configurable: true
  29391. });
  29392. Object.defineProperty(Material, "PointFillMode", {
  29393. get: function () {
  29394. return Material._PointFillMode;
  29395. },
  29396. enumerable: true,
  29397. configurable: true
  29398. });
  29399. Object.defineProperty(Material, "PointListDrawMode", {
  29400. get: function () {
  29401. return Material._PointListDrawMode;
  29402. },
  29403. enumerable: true,
  29404. configurable: true
  29405. });
  29406. Object.defineProperty(Material, "LineListDrawMode", {
  29407. get: function () {
  29408. return Material._LineListDrawMode;
  29409. },
  29410. enumerable: true,
  29411. configurable: true
  29412. });
  29413. Object.defineProperty(Material, "LineLoopDrawMode", {
  29414. get: function () {
  29415. return Material._LineLoopDrawMode;
  29416. },
  29417. enumerable: true,
  29418. configurable: true
  29419. });
  29420. Object.defineProperty(Material, "LineStripDrawMode", {
  29421. get: function () {
  29422. return Material._LineStripDrawMode;
  29423. },
  29424. enumerable: true,
  29425. configurable: true
  29426. });
  29427. Object.defineProperty(Material, "TriangleStripDrawMode", {
  29428. get: function () {
  29429. return Material._TriangleStripDrawMode;
  29430. },
  29431. enumerable: true,
  29432. configurable: true
  29433. });
  29434. Object.defineProperty(Material, "TriangleFanDrawMode", {
  29435. get: function () {
  29436. return Material._TriangleFanDrawMode;
  29437. },
  29438. enumerable: true,
  29439. configurable: true
  29440. });
  29441. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29442. get: function () {
  29443. return Material._ClockWiseSideOrientation;
  29444. },
  29445. enumerable: true,
  29446. configurable: true
  29447. });
  29448. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29449. get: function () {
  29450. return Material._CounterClockWiseSideOrientation;
  29451. },
  29452. enumerable: true,
  29453. configurable: true
  29454. });
  29455. Object.defineProperty(Material, "TextureDirtyFlag", {
  29456. get: function () {
  29457. return Material._TextureDirtyFlag;
  29458. },
  29459. enumerable: true,
  29460. configurable: true
  29461. });
  29462. Object.defineProperty(Material, "LightDirtyFlag", {
  29463. get: function () {
  29464. return Material._LightDirtyFlag;
  29465. },
  29466. enumerable: true,
  29467. configurable: true
  29468. });
  29469. Object.defineProperty(Material, "FresnelDirtyFlag", {
  29470. get: function () {
  29471. return Material._FresnelDirtyFlag;
  29472. },
  29473. enumerable: true,
  29474. configurable: true
  29475. });
  29476. Object.defineProperty(Material, "AttributesDirtyFlag", {
  29477. get: function () {
  29478. return Material._AttributesDirtyFlag;
  29479. },
  29480. enumerable: true,
  29481. configurable: true
  29482. });
  29483. Object.defineProperty(Material, "MiscDirtyFlag", {
  29484. get: function () {
  29485. return Material._MiscDirtyFlag;
  29486. },
  29487. enumerable: true,
  29488. configurable: true
  29489. });
  29490. Object.defineProperty(Material.prototype, "alpha", {
  29491. get: function () {
  29492. return this._alpha;
  29493. },
  29494. set: function (value) {
  29495. if (this._alpha === value) {
  29496. return;
  29497. }
  29498. this._alpha = value;
  29499. this.markAsDirty(Material.MiscDirtyFlag);
  29500. },
  29501. enumerable: true,
  29502. configurable: true
  29503. });
  29504. Object.defineProperty(Material.prototype, "backFaceCulling", {
  29505. get: function () {
  29506. return this._backFaceCulling;
  29507. },
  29508. set: function (value) {
  29509. if (this._backFaceCulling === value) {
  29510. return;
  29511. }
  29512. this._backFaceCulling = value;
  29513. this.markAsDirty(Material.TextureDirtyFlag);
  29514. },
  29515. enumerable: true,
  29516. configurable: true
  29517. });
  29518. Object.defineProperty(Material.prototype, "onDispose", {
  29519. set: function (callback) {
  29520. if (this._onDisposeObserver) {
  29521. this.onDisposeObservable.remove(this._onDisposeObserver);
  29522. }
  29523. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29524. },
  29525. enumerable: true,
  29526. configurable: true
  29527. });
  29528. Object.defineProperty(Material.prototype, "onBind", {
  29529. set: function (callback) {
  29530. if (this._onBindObserver) {
  29531. this.onBindObservable.remove(this._onBindObserver);
  29532. }
  29533. this._onBindObserver = this.onBindObservable.add(callback);
  29534. },
  29535. enumerable: true,
  29536. configurable: true
  29537. });
  29538. Object.defineProperty(Material.prototype, "alphaMode", {
  29539. get: function () {
  29540. return this._alphaMode;
  29541. },
  29542. set: function (value) {
  29543. if (this._alphaMode === value) {
  29544. return;
  29545. }
  29546. this._alphaMode = value;
  29547. this.markAsDirty(Material.TextureDirtyFlag);
  29548. },
  29549. enumerable: true,
  29550. configurable: true
  29551. });
  29552. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  29553. get: function () {
  29554. return this._needDepthPrePass;
  29555. },
  29556. set: function (value) {
  29557. if (this._needDepthPrePass === value) {
  29558. return;
  29559. }
  29560. this._needDepthPrePass = value;
  29561. if (this._needDepthPrePass) {
  29562. this.checkReadyOnEveryCall = true;
  29563. }
  29564. },
  29565. enumerable: true,
  29566. configurable: true
  29567. });
  29568. Object.defineProperty(Material.prototype, "fogEnabled", {
  29569. get: function () {
  29570. return this._fogEnabled;
  29571. },
  29572. set: function (value) {
  29573. if (this._fogEnabled === value) {
  29574. return;
  29575. }
  29576. this._fogEnabled = value;
  29577. this.markAsDirty(Material.MiscDirtyFlag);
  29578. },
  29579. enumerable: true,
  29580. configurable: true
  29581. });
  29582. Object.defineProperty(Material.prototype, "wireframe", {
  29583. get: function () {
  29584. return this._fillMode === Material.WireFrameFillMode;
  29585. },
  29586. set: function (value) {
  29587. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29588. },
  29589. enumerable: true,
  29590. configurable: true
  29591. });
  29592. Object.defineProperty(Material.prototype, "pointsCloud", {
  29593. get: function () {
  29594. return this._fillMode === Material.PointFillMode;
  29595. },
  29596. set: function (value) {
  29597. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29598. },
  29599. enumerable: true,
  29600. configurable: true
  29601. });
  29602. Object.defineProperty(Material.prototype, "fillMode", {
  29603. get: function () {
  29604. return this._fillMode;
  29605. },
  29606. set: function (value) {
  29607. if (this._fillMode === value) {
  29608. return;
  29609. }
  29610. this._fillMode = value;
  29611. this.markAsDirty(Material.MiscDirtyFlag);
  29612. },
  29613. enumerable: true,
  29614. configurable: true
  29615. });
  29616. /**
  29617. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29618. * subclasses should override adding information pertainent to themselves
  29619. */
  29620. Material.prototype.toString = function (fullDetails) {
  29621. var ret = "Name: " + this.name;
  29622. if (fullDetails) {
  29623. }
  29624. return ret;
  29625. };
  29626. /**
  29627. * Child classes can use it to update shaders
  29628. */
  29629. Material.prototype.getClassName = function () {
  29630. return "Material";
  29631. };
  29632. Object.defineProperty(Material.prototype, "isFrozen", {
  29633. get: function () {
  29634. return this.checkReadyOnlyOnce;
  29635. },
  29636. enumerable: true,
  29637. configurable: true
  29638. });
  29639. Material.prototype.freeze = function () {
  29640. this.checkReadyOnlyOnce = true;
  29641. };
  29642. Material.prototype.unfreeze = function () {
  29643. this.checkReadyOnlyOnce = false;
  29644. };
  29645. Material.prototype.isReady = function (mesh, useInstances) {
  29646. return true;
  29647. };
  29648. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29649. return false;
  29650. };
  29651. Material.prototype.getEffect = function () {
  29652. return this._effect;
  29653. };
  29654. Material.prototype.getScene = function () {
  29655. return this._scene;
  29656. };
  29657. Material.prototype.needAlphaBlending = function () {
  29658. return (this.alpha < 1.0);
  29659. };
  29660. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  29661. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  29662. };
  29663. Material.prototype.needAlphaTesting = function () {
  29664. return false;
  29665. };
  29666. Material.prototype.getAlphaTestTexture = function () {
  29667. return null;
  29668. };
  29669. Material.prototype.markDirty = function () {
  29670. this._wasPreviouslyReady = false;
  29671. };
  29672. Material.prototype._preBind = function (effect, overrideOrientation) {
  29673. if (overrideOrientation === void 0) { overrideOrientation = null; }
  29674. var engine = this._scene.getEngine();
  29675. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  29676. var reverse = orientation === Material.ClockWiseSideOrientation;
  29677. engine.enableEffect(effect ? effect : this._effect);
  29678. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29679. return reverse;
  29680. };
  29681. Material.prototype.bind = function (world, mesh) {
  29682. };
  29683. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29684. };
  29685. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29686. };
  29687. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  29688. sceneUbo.bindToEffect(effect, "Scene");
  29689. };
  29690. Material.prototype.bindView = function (effect) {
  29691. if (!this._useUBO) {
  29692. effect.setMatrix("view", this.getScene().getViewMatrix());
  29693. }
  29694. else {
  29695. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29696. }
  29697. };
  29698. Material.prototype.bindViewProjection = function (effect) {
  29699. if (!this._useUBO) {
  29700. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29701. }
  29702. else {
  29703. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29704. }
  29705. };
  29706. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  29707. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  29708. };
  29709. Material.prototype._afterBind = function (mesh) {
  29710. this._scene._cachedMaterial = this;
  29711. if (mesh) {
  29712. this._scene._cachedVisibility = mesh.visibility;
  29713. }
  29714. else {
  29715. this._scene._cachedVisibility = 1;
  29716. }
  29717. if (mesh) {
  29718. this.onBindObservable.notifyObservers(mesh);
  29719. }
  29720. if (this.disableDepthWrite) {
  29721. var engine = this._scene.getEngine();
  29722. this._cachedDepthWriteState = engine.getDepthWrite();
  29723. engine.setDepthWrite(false);
  29724. }
  29725. };
  29726. Material.prototype.unbind = function () {
  29727. this.onUnBindObservable.notifyObservers(this);
  29728. if (this.disableDepthWrite) {
  29729. var engine = this._scene.getEngine();
  29730. engine.setDepthWrite(this._cachedDepthWriteState);
  29731. }
  29732. };
  29733. Material.prototype.getActiveTextures = function () {
  29734. return [];
  29735. };
  29736. Material.prototype.hasTexture = function (texture) {
  29737. return false;
  29738. };
  29739. Material.prototype.clone = function (name) {
  29740. return null;
  29741. };
  29742. Material.prototype.getBindedMeshes = function () {
  29743. var result = new Array();
  29744. for (var index = 0; index < this._scene.meshes.length; index++) {
  29745. var mesh = this._scene.meshes[index];
  29746. if (mesh.material === this) {
  29747. result.push(mesh);
  29748. }
  29749. }
  29750. return result;
  29751. };
  29752. /**
  29753. * Force shader compilation including textures ready check
  29754. */
  29755. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  29756. var _this = this;
  29757. var localOptions = __assign({ clipPlane: false }, options);
  29758. var subMesh = new BABYLON.BaseSubMesh();
  29759. var scene = this.getScene();
  29760. var checkReady = function () {
  29761. if (!_this._scene || !_this._scene.getEngine()) {
  29762. return;
  29763. }
  29764. if (subMesh._materialDefines) {
  29765. subMesh._materialDefines._renderId = -1;
  29766. }
  29767. var clipPlaneState = scene.clipPlane;
  29768. if (localOptions.clipPlane) {
  29769. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29770. }
  29771. if (_this.storeEffectOnSubMeshes) {
  29772. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29773. if (onCompiled) {
  29774. onCompiled(_this);
  29775. }
  29776. }
  29777. else {
  29778. setTimeout(checkReady, 16);
  29779. }
  29780. }
  29781. else {
  29782. if (_this.isReady(mesh)) {
  29783. if (onCompiled) {
  29784. onCompiled(_this);
  29785. }
  29786. }
  29787. else {
  29788. setTimeout(checkReady, 16);
  29789. }
  29790. }
  29791. if (options && options.clipPlane) {
  29792. scene.clipPlane = clipPlaneState;
  29793. }
  29794. };
  29795. checkReady();
  29796. };
  29797. Material.prototype.markAsDirty = function (flag) {
  29798. if (flag & Material.TextureDirtyFlag) {
  29799. this._markAllSubMeshesAsTexturesDirty();
  29800. }
  29801. if (flag & Material.LightDirtyFlag) {
  29802. this._markAllSubMeshesAsLightsDirty();
  29803. }
  29804. if (flag & Material.FresnelDirtyFlag) {
  29805. this._markAllSubMeshesAsFresnelDirty();
  29806. }
  29807. if (flag & Material.AttributesDirtyFlag) {
  29808. this._markAllSubMeshesAsAttributesDirty();
  29809. }
  29810. if (flag & Material.MiscDirtyFlag) {
  29811. this._markAllSubMeshesAsMiscDirty();
  29812. }
  29813. this.getScene().resetCachedMaterial();
  29814. };
  29815. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29816. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29817. var mesh = _a[_i];
  29818. if (!mesh.subMeshes) {
  29819. continue;
  29820. }
  29821. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29822. var subMesh = _c[_b];
  29823. if (subMesh.getMaterial() !== this) {
  29824. continue;
  29825. }
  29826. if (!subMesh._materialDefines) {
  29827. continue;
  29828. }
  29829. func(subMesh._materialDefines);
  29830. }
  29831. }
  29832. };
  29833. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29834. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29835. };
  29836. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29837. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29838. };
  29839. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29840. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29841. };
  29842. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  29843. this._markAllSubMeshesAsDirty(function (defines) {
  29844. defines.markAsFresnelDirty();
  29845. defines.markAsMiscDirty();
  29846. });
  29847. };
  29848. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29849. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29850. };
  29851. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29852. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29853. };
  29854. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29855. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29856. };
  29857. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  29858. this._markAllSubMeshesAsDirty(function (defines) {
  29859. defines.markAsTexturesDirty();
  29860. defines.markAsMiscDirty();
  29861. });
  29862. };
  29863. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29864. // Animations
  29865. this.getScene().stopAnimation(this);
  29866. // Remove from scene
  29867. var index = this._scene.materials.indexOf(this);
  29868. if (index >= 0) {
  29869. this._scene.materials.splice(index, 1);
  29870. }
  29871. // Remove from meshes
  29872. for (index = 0; index < this._scene.meshes.length; index++) {
  29873. var mesh = this._scene.meshes[index];
  29874. if (mesh.material === this) {
  29875. mesh.material = null;
  29876. if (mesh.geometry) {
  29877. var geometry = (mesh.geometry);
  29878. if (this.storeEffectOnSubMeshes) {
  29879. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29880. var subMesh = _a[_i];
  29881. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29882. if (forceDisposeEffect && subMesh._materialEffect) {
  29883. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29884. }
  29885. }
  29886. }
  29887. else {
  29888. geometry._releaseVertexArrayObject(this._effect);
  29889. }
  29890. }
  29891. }
  29892. }
  29893. this._uniformBuffer.dispose();
  29894. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29895. if (forceDisposeEffect && this._effect) {
  29896. if (!this.storeEffectOnSubMeshes) {
  29897. this._scene.getEngine()._releaseEffect(this._effect);
  29898. }
  29899. this._effect = null;
  29900. }
  29901. // Callback
  29902. this.onDisposeObservable.notifyObservers(this);
  29903. this.onDisposeObservable.clear();
  29904. this.onBindObservable.clear();
  29905. this.onUnBindObservable.clear();
  29906. };
  29907. Material.prototype.serialize = function () {
  29908. return BABYLON.SerializationHelper.Serialize(this);
  29909. };
  29910. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29911. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29912. multiMaterial.id = parsedMultiMaterial.id;
  29913. if (BABYLON.Tags) {
  29914. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29915. }
  29916. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29917. var subMatId = parsedMultiMaterial.materials[matIndex];
  29918. if (subMatId) {
  29919. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29920. }
  29921. else {
  29922. multiMaterial.subMaterials.push(null);
  29923. }
  29924. }
  29925. return multiMaterial;
  29926. };
  29927. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29928. if (!parsedMaterial.customType) {
  29929. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29930. }
  29931. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29932. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29933. if (!BABYLON.LegacyPBRMaterial) {
  29934. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29935. return;
  29936. }
  29937. }
  29938. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29939. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29940. ;
  29941. };
  29942. // Triangle views
  29943. Material._TriangleFillMode = 0;
  29944. Material._WireFrameFillMode = 1;
  29945. Material._PointFillMode = 2;
  29946. // Draw modes
  29947. Material._PointListDrawMode = 3;
  29948. Material._LineListDrawMode = 4;
  29949. Material._LineLoopDrawMode = 5;
  29950. Material._LineStripDrawMode = 6;
  29951. Material._TriangleStripDrawMode = 7;
  29952. Material._TriangleFanDrawMode = 8;
  29953. Material._ClockWiseSideOrientation = 0;
  29954. Material._CounterClockWiseSideOrientation = 1;
  29955. Material._TextureDirtyFlag = 1;
  29956. Material._LightDirtyFlag = 2;
  29957. Material._FresnelDirtyFlag = 4;
  29958. Material._AttributesDirtyFlag = 8;
  29959. Material._MiscDirtyFlag = 16;
  29960. __decorate([
  29961. BABYLON.serialize()
  29962. ], Material.prototype, "id", void 0);
  29963. __decorate([
  29964. BABYLON.serialize()
  29965. ], Material.prototype, "name", void 0);
  29966. __decorate([
  29967. BABYLON.serialize()
  29968. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29969. __decorate([
  29970. BABYLON.serialize()
  29971. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29972. __decorate([
  29973. BABYLON.serialize()
  29974. ], Material.prototype, "state", void 0);
  29975. __decorate([
  29976. BABYLON.serialize("alpha")
  29977. ], Material.prototype, "_alpha", void 0);
  29978. __decorate([
  29979. BABYLON.serialize("backFaceCulling")
  29980. ], Material.prototype, "_backFaceCulling", void 0);
  29981. __decorate([
  29982. BABYLON.serialize()
  29983. ], Material.prototype, "sideOrientation", void 0);
  29984. __decorate([
  29985. BABYLON.serialize("alphaMode")
  29986. ], Material.prototype, "_alphaMode", void 0);
  29987. __decorate([
  29988. BABYLON.serialize()
  29989. ], Material.prototype, "_needDepthPrePass", void 0);
  29990. __decorate([
  29991. BABYLON.serialize()
  29992. ], Material.prototype, "disableDepthWrite", void 0);
  29993. __decorate([
  29994. BABYLON.serialize()
  29995. ], Material.prototype, "forceDepthWrite", void 0);
  29996. __decorate([
  29997. BABYLON.serialize()
  29998. ], Material.prototype, "separateCullingPass", void 0);
  29999. __decorate([
  30000. BABYLON.serialize("fogEnabled")
  30001. ], Material.prototype, "_fogEnabled", void 0);
  30002. __decorate([
  30003. BABYLON.serialize()
  30004. ], Material.prototype, "pointSize", void 0);
  30005. __decorate([
  30006. BABYLON.serialize()
  30007. ], Material.prototype, "zOffset", void 0);
  30008. __decorate([
  30009. BABYLON.serialize()
  30010. ], Material.prototype, "wireframe", null);
  30011. __decorate([
  30012. BABYLON.serialize()
  30013. ], Material.prototype, "pointsCloud", null);
  30014. __decorate([
  30015. BABYLON.serialize()
  30016. ], Material.prototype, "fillMode", null);
  30017. return Material;
  30018. }());
  30019. BABYLON.Material = Material;
  30020. })(BABYLON || (BABYLON = {}));
  30021. //# sourceMappingURL=babylon.material.js.map
  30022. var BABYLON;
  30023. (function (BABYLON) {
  30024. var UniformBuffer = /** @class */ (function () {
  30025. /**
  30026. * Uniform buffer objects.
  30027. *
  30028. * Handles blocks of uniform on the GPU.
  30029. *
  30030. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  30031. *
  30032. * For more information, please refer to :
  30033. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  30034. */
  30035. function UniformBuffer(engine, data, dynamic) {
  30036. this._engine = engine;
  30037. this._noUBO = !engine.supportsUniformBuffers;
  30038. this._dynamic = dynamic;
  30039. this._data = data || [];
  30040. this._uniformLocations = {};
  30041. this._uniformSizes = {};
  30042. this._uniformLocationPointer = 0;
  30043. this._needSync = false;
  30044. if (this._noUBO) {
  30045. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  30046. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  30047. this.updateFloat = this._updateFloatForEffect;
  30048. this.updateFloat2 = this._updateFloat2ForEffect;
  30049. this.updateFloat3 = this._updateFloat3ForEffect;
  30050. this.updateFloat4 = this._updateFloat4ForEffect;
  30051. this.updateMatrix = this._updateMatrixForEffect;
  30052. this.updateVector3 = this._updateVector3ForEffect;
  30053. this.updateVector4 = this._updateVector4ForEffect;
  30054. this.updateColor3 = this._updateColor3ForEffect;
  30055. this.updateColor4 = this._updateColor4ForEffect;
  30056. }
  30057. else {
  30058. this._engine._uniformBuffers.push(this);
  30059. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  30060. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  30061. this.updateFloat = this._updateFloatForUniform;
  30062. this.updateFloat2 = this._updateFloat2ForUniform;
  30063. this.updateFloat3 = this._updateFloat3ForUniform;
  30064. this.updateFloat4 = this._updateFloat4ForUniform;
  30065. this.updateMatrix = this._updateMatrixForUniform;
  30066. this.updateVector3 = this._updateVector3ForUniform;
  30067. this.updateVector4 = this._updateVector4ForUniform;
  30068. this.updateColor3 = this._updateColor3ForUniform;
  30069. this.updateColor4 = this._updateColor4ForUniform;
  30070. }
  30071. }
  30072. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  30073. // Properties
  30074. /**
  30075. * Indicates if the buffer is using the WebGL2 UBO implementation,
  30076. * or just falling back on setUniformXXX calls.
  30077. */
  30078. get: function () {
  30079. return !this._noUBO;
  30080. },
  30081. enumerable: true,
  30082. configurable: true
  30083. });
  30084. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  30085. /**
  30086. * Indicates if the WebGL underlying uniform buffer is in sync
  30087. * with the javascript cache data.
  30088. */
  30089. get: function () {
  30090. return !this._needSync;
  30091. },
  30092. enumerable: true,
  30093. configurable: true
  30094. });
  30095. /**
  30096. * Indicates if the WebGL underlying uniform buffer is dynamic.
  30097. * Also, a dynamic UniformBuffer will disable cache verification and always
  30098. * update the underlying WebGL uniform buffer to the GPU.
  30099. */
  30100. UniformBuffer.prototype.isDynamic = function () {
  30101. return this._dynamic !== undefined;
  30102. };
  30103. /**
  30104. * The data cache on JS side.
  30105. */
  30106. UniformBuffer.prototype.getData = function () {
  30107. return this._bufferData;
  30108. };
  30109. /**
  30110. * The underlying WebGL Uniform buffer.
  30111. */
  30112. UniformBuffer.prototype.getBuffer = function () {
  30113. return this._buffer;
  30114. };
  30115. /**
  30116. * std140 layout specifies how to align data within an UBO structure.
  30117. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  30118. * for specs.
  30119. */
  30120. UniformBuffer.prototype._fillAlignment = function (size) {
  30121. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  30122. // and 4x4 matrices
  30123. // TODO : change if other types are used
  30124. var alignment;
  30125. if (size <= 2) {
  30126. alignment = size;
  30127. }
  30128. else {
  30129. alignment = 4;
  30130. }
  30131. if ((this._uniformLocationPointer % alignment) !== 0) {
  30132. var oldPointer = this._uniformLocationPointer;
  30133. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  30134. var diff = this._uniformLocationPointer - oldPointer;
  30135. for (var i = 0; i < diff; i++) {
  30136. this._data.push(0);
  30137. }
  30138. }
  30139. };
  30140. /**
  30141. * Adds an uniform in the buffer.
  30142. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  30143. * for the layout to be correct !
  30144. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30145. * @param {number|number[]} size Data size, or data directly.
  30146. */
  30147. UniformBuffer.prototype.addUniform = function (name, size) {
  30148. if (this._noUBO) {
  30149. return;
  30150. }
  30151. if (this._uniformLocations[name] !== undefined) {
  30152. // Already existing uniform
  30153. return;
  30154. }
  30155. // This function must be called in the order of the shader layout !
  30156. // size can be the size of the uniform, or data directly
  30157. var data;
  30158. if (size instanceof Array) {
  30159. data = size;
  30160. size = data.length;
  30161. }
  30162. else {
  30163. size = size;
  30164. data = [];
  30165. // Fill with zeros
  30166. for (var i = 0; i < size; i++) {
  30167. data.push(0);
  30168. }
  30169. }
  30170. this._fillAlignment(size);
  30171. this._uniformSizes[name] = size;
  30172. this._uniformLocations[name] = this._uniformLocationPointer;
  30173. this._uniformLocationPointer += size;
  30174. for (var i = 0; i < size; i++) {
  30175. this._data.push(data[i]);
  30176. }
  30177. this._needSync = true;
  30178. };
  30179. /**
  30180. * Wrapper for addUniform.
  30181. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30182. * @param {Matrix} mat A 4x4 matrix.
  30183. */
  30184. UniformBuffer.prototype.addMatrix = function (name, mat) {
  30185. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  30186. };
  30187. /**
  30188. * Wrapper for addUniform.
  30189. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30190. * @param {number} x
  30191. * @param {number} y
  30192. */
  30193. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  30194. var temp = [x, y];
  30195. this.addUniform(name, temp);
  30196. };
  30197. /**
  30198. * Wrapper for addUniform.
  30199. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30200. * @param {number} x
  30201. * @param {number} y
  30202. * @param {number} z
  30203. */
  30204. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  30205. var temp = [x, y, z];
  30206. this.addUniform(name, temp);
  30207. };
  30208. /**
  30209. * Wrapper for addUniform.
  30210. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30211. * @param {Color3} color
  30212. */
  30213. UniformBuffer.prototype.addColor3 = function (name, color) {
  30214. var temp = new Array();
  30215. color.toArray(temp);
  30216. this.addUniform(name, temp);
  30217. };
  30218. /**
  30219. * Wrapper for addUniform.
  30220. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30221. * @param {Color3} color
  30222. * @param {number} alpha
  30223. */
  30224. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  30225. var temp = new Array();
  30226. color.toArray(temp);
  30227. temp.push(alpha);
  30228. this.addUniform(name, temp);
  30229. };
  30230. /**
  30231. * Wrapper for addUniform.
  30232. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30233. * @param {Vector3} vector
  30234. */
  30235. UniformBuffer.prototype.addVector3 = function (name, vector) {
  30236. var temp = new Array();
  30237. vector.toArray(temp);
  30238. this.addUniform(name, temp);
  30239. };
  30240. /**
  30241. * Wrapper for addUniform.
  30242. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30243. */
  30244. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  30245. this.addUniform(name, 12);
  30246. };
  30247. /**
  30248. * Wrapper for addUniform.
  30249. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30250. */
  30251. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  30252. this.addUniform(name, 8);
  30253. };
  30254. /**
  30255. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  30256. */
  30257. UniformBuffer.prototype.create = function () {
  30258. if (this._noUBO) {
  30259. return;
  30260. }
  30261. if (this._buffer) {
  30262. return; // nothing to do
  30263. }
  30264. // See spec, alignment must be filled as a vec4
  30265. this._fillAlignment(4);
  30266. this._bufferData = new Float32Array(this._data);
  30267. this._rebuild();
  30268. this._needSync = true;
  30269. };
  30270. UniformBuffer.prototype._rebuild = function () {
  30271. if (this._noUBO) {
  30272. return;
  30273. }
  30274. if (this._dynamic) {
  30275. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  30276. }
  30277. else {
  30278. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  30279. }
  30280. };
  30281. /**
  30282. * Updates the WebGL Uniform Buffer on the GPU.
  30283. * If the `dynamic` flag is set to true, no cache comparison is done.
  30284. * Otherwise, the buffer will be updated only if the cache differs.
  30285. */
  30286. UniformBuffer.prototype.update = function () {
  30287. if (!this._buffer) {
  30288. this.create();
  30289. return;
  30290. }
  30291. if (!this._dynamic && !this._needSync) {
  30292. return;
  30293. }
  30294. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  30295. this._needSync = false;
  30296. };
  30297. /**
  30298. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  30299. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30300. * @param {number[]|Float32Array} data Flattened data
  30301. * @param {number} size Size of the data.
  30302. */
  30303. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  30304. var location = this._uniformLocations[uniformName];
  30305. if (location === undefined) {
  30306. if (this._buffer) {
  30307. // Cannot add an uniform if the buffer is already created
  30308. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  30309. return;
  30310. }
  30311. this.addUniform(uniformName, size);
  30312. location = this._uniformLocations[uniformName];
  30313. }
  30314. if (!this._buffer) {
  30315. this.create();
  30316. }
  30317. if (!this._dynamic) {
  30318. // Cache for static uniform buffers
  30319. var changed = false;
  30320. for (var i = 0; i < size; i++) {
  30321. if (this._bufferData[location + i] !== data[i]) {
  30322. changed = true;
  30323. this._bufferData[location + i] = data[i];
  30324. }
  30325. }
  30326. this._needSync = this._needSync || changed;
  30327. }
  30328. else {
  30329. // No cache for dynamic
  30330. for (var i = 0; i < size; i++) {
  30331. this._bufferData[location + i] = data[i];
  30332. }
  30333. }
  30334. };
  30335. // Update methods
  30336. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  30337. // To match std140, matrix must be realigned
  30338. for (var i = 0; i < 3; i++) {
  30339. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  30340. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  30341. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  30342. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30343. }
  30344. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  30345. };
  30346. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  30347. this._currentEffect.setMatrix3x3(name, matrix);
  30348. };
  30349. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  30350. this._currentEffect.setMatrix2x2(name, matrix);
  30351. };
  30352. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  30353. // To match std140, matrix must be realigned
  30354. for (var i = 0; i < 2; i++) {
  30355. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  30356. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  30357. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  30358. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30359. }
  30360. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  30361. };
  30362. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  30363. this._currentEffect.setFloat(name, x);
  30364. };
  30365. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  30366. UniformBuffer._tempBuffer[0] = x;
  30367. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  30368. };
  30369. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  30370. if (suffix === void 0) { suffix = ""; }
  30371. this._currentEffect.setFloat2(name + suffix, x, y);
  30372. };
  30373. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  30374. if (suffix === void 0) { suffix = ""; }
  30375. UniformBuffer._tempBuffer[0] = x;
  30376. UniformBuffer._tempBuffer[1] = y;
  30377. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  30378. };
  30379. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  30380. if (suffix === void 0) { suffix = ""; }
  30381. this._currentEffect.setFloat3(name + suffix, x, y, z);
  30382. };
  30383. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  30384. if (suffix === void 0) { suffix = ""; }
  30385. UniformBuffer._tempBuffer[0] = x;
  30386. UniformBuffer._tempBuffer[1] = y;
  30387. UniformBuffer._tempBuffer[2] = z;
  30388. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30389. };
  30390. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  30391. if (suffix === void 0) { suffix = ""; }
  30392. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  30393. };
  30394. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  30395. if (suffix === void 0) { suffix = ""; }
  30396. UniformBuffer._tempBuffer[0] = x;
  30397. UniformBuffer._tempBuffer[1] = y;
  30398. UniformBuffer._tempBuffer[2] = z;
  30399. UniformBuffer._tempBuffer[3] = w;
  30400. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30401. };
  30402. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  30403. this._currentEffect.setMatrix(name, mat);
  30404. };
  30405. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  30406. this.updateUniform(name, mat.toArray(), 16);
  30407. };
  30408. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  30409. this._currentEffect.setVector3(name, vector);
  30410. };
  30411. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  30412. vector.toArray(UniformBuffer._tempBuffer);
  30413. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30414. };
  30415. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  30416. this._currentEffect.setVector4(name, vector);
  30417. };
  30418. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  30419. vector.toArray(UniformBuffer._tempBuffer);
  30420. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30421. };
  30422. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  30423. if (suffix === void 0) { suffix = ""; }
  30424. this._currentEffect.setColor3(name + suffix, color);
  30425. };
  30426. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  30427. if (suffix === void 0) { suffix = ""; }
  30428. color.toArray(UniformBuffer._tempBuffer);
  30429. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30430. };
  30431. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  30432. if (suffix === void 0) { suffix = ""; }
  30433. this._currentEffect.setColor4(name + suffix, color, alpha);
  30434. };
  30435. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  30436. if (suffix === void 0) { suffix = ""; }
  30437. color.toArray(UniformBuffer._tempBuffer);
  30438. UniformBuffer._tempBuffer[3] = alpha;
  30439. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30440. };
  30441. /**
  30442. * Sets a sampler uniform on the effect.
  30443. * @param {string} name Name of the sampler.
  30444. * @param {Texture} texture
  30445. */
  30446. UniformBuffer.prototype.setTexture = function (name, texture) {
  30447. this._currentEffect.setTexture(name, texture);
  30448. };
  30449. /**
  30450. * Directly updates the value of the uniform in the cache AND on the GPU.
  30451. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30452. * @param {number[]|Float32Array} data Flattened data
  30453. */
  30454. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  30455. this.updateUniform(uniformName, data, data.length);
  30456. this.update();
  30457. };
  30458. /**
  30459. * Binds this uniform buffer to an effect.
  30460. * @param {Effect} effect
  30461. * @param {string} name Name of the uniform block in the shader.
  30462. */
  30463. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  30464. this._currentEffect = effect;
  30465. if (this._noUBO || !this._buffer) {
  30466. return;
  30467. }
  30468. effect.bindUniformBuffer(this._buffer, name);
  30469. };
  30470. /**
  30471. * Disposes the uniform buffer.
  30472. */
  30473. UniformBuffer.prototype.dispose = function () {
  30474. if (this._noUBO) {
  30475. return;
  30476. }
  30477. var index = this._engine._uniformBuffers.indexOf(this);
  30478. if (index !== -1) {
  30479. this._engine._uniformBuffers.splice(index, 1);
  30480. }
  30481. if (!this._buffer) {
  30482. return;
  30483. }
  30484. if (this._engine._releaseBuffer(this._buffer)) {
  30485. this._buffer = null;
  30486. }
  30487. };
  30488. // Pool for avoiding memory leaks
  30489. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  30490. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  30491. return UniformBuffer;
  30492. }());
  30493. BABYLON.UniformBuffer = UniformBuffer;
  30494. })(BABYLON || (BABYLON = {}));
  30495. //# sourceMappingURL=babylon.uniformBuffer.js.map
  30496. var BABYLON;
  30497. (function (BABYLON) {
  30498. var VertexData = /** @class */ (function () {
  30499. function VertexData() {
  30500. }
  30501. VertexData.prototype.set = function (data, kind) {
  30502. switch (kind) {
  30503. case BABYLON.VertexBuffer.PositionKind:
  30504. this.positions = data;
  30505. break;
  30506. case BABYLON.VertexBuffer.NormalKind:
  30507. this.normals = data;
  30508. break;
  30509. case BABYLON.VertexBuffer.TangentKind:
  30510. this.tangents = data;
  30511. break;
  30512. case BABYLON.VertexBuffer.UVKind:
  30513. this.uvs = data;
  30514. break;
  30515. case BABYLON.VertexBuffer.UV2Kind:
  30516. this.uvs2 = data;
  30517. break;
  30518. case BABYLON.VertexBuffer.UV3Kind:
  30519. this.uvs3 = data;
  30520. break;
  30521. case BABYLON.VertexBuffer.UV4Kind:
  30522. this.uvs4 = data;
  30523. break;
  30524. case BABYLON.VertexBuffer.UV5Kind:
  30525. this.uvs5 = data;
  30526. break;
  30527. case BABYLON.VertexBuffer.UV6Kind:
  30528. this.uvs6 = data;
  30529. break;
  30530. case BABYLON.VertexBuffer.ColorKind:
  30531. this.colors = data;
  30532. break;
  30533. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30534. this.matricesIndices = data;
  30535. break;
  30536. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30537. this.matricesWeights = data;
  30538. break;
  30539. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30540. this.matricesIndicesExtra = data;
  30541. break;
  30542. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30543. this.matricesWeightsExtra = data;
  30544. break;
  30545. }
  30546. };
  30547. /**
  30548. * Associates the vertexData to the passed Mesh.
  30549. * Sets it as updatable or not (default `false`).
  30550. * Returns the VertexData.
  30551. */
  30552. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30553. this._applyTo(mesh, updatable);
  30554. return this;
  30555. };
  30556. /**
  30557. * Associates the vertexData to the passed Geometry.
  30558. * Sets it as updatable or not (default `false`).
  30559. * Returns the VertexData.
  30560. */
  30561. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30562. this._applyTo(geometry, updatable);
  30563. return this;
  30564. };
  30565. /**
  30566. * Updates the associated mesh.
  30567. * Returns the VertexData.
  30568. */
  30569. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30570. this._update(mesh);
  30571. return this;
  30572. };
  30573. /**
  30574. * Updates the associated geometry.
  30575. * Returns the VertexData.
  30576. */
  30577. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30578. this._update(geometry);
  30579. return this;
  30580. };
  30581. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30582. if (updatable === void 0) { updatable = false; }
  30583. if (this.positions) {
  30584. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30585. }
  30586. if (this.normals) {
  30587. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30588. }
  30589. if (this.tangents) {
  30590. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  30591. }
  30592. if (this.uvs) {
  30593. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30594. }
  30595. if (this.uvs2) {
  30596. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30597. }
  30598. if (this.uvs3) {
  30599. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30600. }
  30601. if (this.uvs4) {
  30602. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30603. }
  30604. if (this.uvs5) {
  30605. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30606. }
  30607. if (this.uvs6) {
  30608. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30609. }
  30610. if (this.colors) {
  30611. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30612. }
  30613. if (this.matricesIndices) {
  30614. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30615. }
  30616. if (this.matricesWeights) {
  30617. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30618. }
  30619. if (this.matricesIndicesExtra) {
  30620. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30621. }
  30622. if (this.matricesWeightsExtra) {
  30623. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30624. }
  30625. if (this.indices) {
  30626. meshOrGeometry.setIndices(this.indices, null, updatable);
  30627. }
  30628. return this;
  30629. };
  30630. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30631. if (this.positions) {
  30632. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30633. }
  30634. if (this.normals) {
  30635. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30636. }
  30637. if (this.tangents) {
  30638. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  30639. }
  30640. if (this.uvs) {
  30641. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30642. }
  30643. if (this.uvs2) {
  30644. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30645. }
  30646. if (this.uvs3) {
  30647. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30648. }
  30649. if (this.uvs4) {
  30650. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30651. }
  30652. if (this.uvs5) {
  30653. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30654. }
  30655. if (this.uvs6) {
  30656. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30657. }
  30658. if (this.colors) {
  30659. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30660. }
  30661. if (this.matricesIndices) {
  30662. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30663. }
  30664. if (this.matricesWeights) {
  30665. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30666. }
  30667. if (this.matricesIndicesExtra) {
  30668. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30669. }
  30670. if (this.matricesWeightsExtra) {
  30671. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30672. }
  30673. if (this.indices) {
  30674. meshOrGeometry.setIndices(this.indices, null);
  30675. }
  30676. return this;
  30677. };
  30678. /**
  30679. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  30680. * Returns the VertexData.
  30681. */
  30682. VertexData.prototype.transform = function (matrix) {
  30683. var transformed = BABYLON.Vector3.Zero();
  30684. var index;
  30685. if (this.positions) {
  30686. var position = BABYLON.Vector3.Zero();
  30687. for (index = 0; index < this.positions.length; index += 3) {
  30688. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30689. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30690. this.positions[index] = transformed.x;
  30691. this.positions[index + 1] = transformed.y;
  30692. this.positions[index + 2] = transformed.z;
  30693. }
  30694. }
  30695. if (this.normals) {
  30696. var normal = BABYLON.Vector3.Zero();
  30697. for (index = 0; index < this.normals.length; index += 3) {
  30698. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30699. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30700. this.normals[index] = transformed.x;
  30701. this.normals[index + 1] = transformed.y;
  30702. this.normals[index + 2] = transformed.z;
  30703. }
  30704. }
  30705. if (this.tangents) {
  30706. var tangent = BABYLON.Vector4.Zero();
  30707. var tangentTransformed = BABYLON.Vector4.Zero();
  30708. for (index = 0; index < this.tangents.length; index += 4) {
  30709. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  30710. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  30711. this.tangents[index] = tangentTransformed.x;
  30712. this.tangents[index + 1] = tangentTransformed.y;
  30713. this.tangents[index + 2] = tangentTransformed.z;
  30714. this.tangents[index + 3] = tangentTransformed.w;
  30715. }
  30716. }
  30717. return this;
  30718. };
  30719. /**
  30720. * Merges the passed VertexData into the current one.
  30721. * Returns the modified VertexData.
  30722. */
  30723. VertexData.prototype.merge = function (other, options) {
  30724. options = options || {};
  30725. if (other.indices) {
  30726. if (!this.indices) {
  30727. this.indices = [];
  30728. }
  30729. var offset = this.positions ? this.positions.length / 3 : 0;
  30730. for (var index = 0; index < other.indices.length; index++) {
  30731. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  30732. this.indices.push(other.indices[index] + offset);
  30733. }
  30734. }
  30735. this.positions = this._mergeElement(this.positions, other.positions);
  30736. if (!this.positions) {
  30737. return this;
  30738. }
  30739. var count = this.positions.length / 3;
  30740. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  30741. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  30742. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  30743. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  30744. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  30745. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  30746. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  30747. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  30748. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  30749. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  30750. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  30751. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  30752. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  30753. return this;
  30754. };
  30755. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  30756. if (length === void 0) { length = 0; }
  30757. if (defaultValue === void 0) { defaultValue = 0; }
  30758. if (!other && !source) {
  30759. return null;
  30760. }
  30761. if (!other) {
  30762. var padding = new Float32Array(source.length);
  30763. padding.fill(defaultValue);
  30764. return this._mergeElement(source, padding, length);
  30765. }
  30766. if (!source) {
  30767. if (length === 0 || length === other.length) {
  30768. return other;
  30769. }
  30770. var padding = new Float32Array(length - other.length);
  30771. padding.fill(defaultValue);
  30772. return this._mergeElement(padding, other, length);
  30773. }
  30774. var len = other.length + source.length;
  30775. var isSrcTypedArray = source instanceof Float32Array;
  30776. var isOthTypedArray = other instanceof Float32Array;
  30777. // use non-loop method when the source is Float32Array
  30778. if (isSrcTypedArray) {
  30779. var ret32 = new Float32Array(len);
  30780. ret32.set(source);
  30781. ret32.set(other, source.length);
  30782. return ret32;
  30783. // source is number[], when other is also use concat
  30784. }
  30785. else if (!isOthTypedArray) {
  30786. return source.concat(other);
  30787. // source is a number[], but other is a Float32Array, loop required
  30788. }
  30789. else {
  30790. var ret = source.slice(0); // copy source to a separate array
  30791. for (var i = 0, len = other.length; i < len; i++) {
  30792. ret.push(other[i]);
  30793. }
  30794. return ret;
  30795. }
  30796. };
  30797. /**
  30798. * Serializes the VertexData.
  30799. * Returns a serialized object.
  30800. */
  30801. VertexData.prototype.serialize = function () {
  30802. var serializationObject = this.serialize();
  30803. if (this.positions) {
  30804. serializationObject.positions = this.positions;
  30805. }
  30806. if (this.normals) {
  30807. serializationObject.normals = this.normals;
  30808. }
  30809. if (this.tangents) {
  30810. serializationObject.tangents = this.tangents;
  30811. }
  30812. if (this.uvs) {
  30813. serializationObject.uvs = this.uvs;
  30814. }
  30815. if (this.uvs2) {
  30816. serializationObject.uvs2 = this.uvs2;
  30817. }
  30818. if (this.uvs3) {
  30819. serializationObject.uvs3 = this.uvs3;
  30820. }
  30821. if (this.uvs4) {
  30822. serializationObject.uvs4 = this.uvs4;
  30823. }
  30824. if (this.uvs5) {
  30825. serializationObject.uvs5 = this.uvs5;
  30826. }
  30827. if (this.uvs6) {
  30828. serializationObject.uvs6 = this.uvs6;
  30829. }
  30830. if (this.colors) {
  30831. serializationObject.colors = this.colors;
  30832. }
  30833. if (this.matricesIndices) {
  30834. serializationObject.matricesIndices = this.matricesIndices;
  30835. serializationObject.matricesIndices._isExpanded = true;
  30836. }
  30837. if (this.matricesWeights) {
  30838. serializationObject.matricesWeights = this.matricesWeights;
  30839. }
  30840. if (this.matricesIndicesExtra) {
  30841. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30842. serializationObject.matricesIndicesExtra._isExpanded = true;
  30843. }
  30844. if (this.matricesWeightsExtra) {
  30845. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30846. }
  30847. serializationObject.indices = this.indices;
  30848. return serializationObject;
  30849. };
  30850. // Statics
  30851. /**
  30852. * Returns the object VertexData associated to the passed mesh.
  30853. */
  30854. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30855. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30856. };
  30857. /**
  30858. * Returns the object VertexData associated to the passed geometry.
  30859. */
  30860. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30861. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30862. };
  30863. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30864. var result = new VertexData();
  30865. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30866. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30867. }
  30868. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30869. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30870. }
  30871. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30872. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30873. }
  30874. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30875. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30876. }
  30877. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30878. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30879. }
  30880. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30881. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30882. }
  30883. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30884. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30885. }
  30886. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30887. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30888. }
  30889. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30890. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30891. }
  30892. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30893. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30894. }
  30895. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30896. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30897. }
  30898. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30899. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30900. }
  30901. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30902. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30903. }
  30904. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30905. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30906. }
  30907. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30908. return result;
  30909. };
  30910. /**
  30911. * Creates the vertexData of the Ribbon.
  30912. */
  30913. VertexData.CreateRibbon = function (options) {
  30914. var pathArray = options.pathArray;
  30915. var closeArray = options.closeArray || false;
  30916. var closePath = options.closePath || false;
  30917. var invertUV = options.invertUV || false;
  30918. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30919. var offset = options.offset || defaultOffset;
  30920. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30921. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30922. var customUV = options.uvs;
  30923. var customColors = options.colors;
  30924. var positions = [];
  30925. var indices = [];
  30926. var normals = [];
  30927. var uvs = [];
  30928. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30929. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30930. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30931. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30932. var minlg; // minimal length among all paths from pathArray
  30933. var lg = []; // array of path lengths : nb of vertex per path
  30934. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30935. var p; // path iterator
  30936. var i; // point iterator
  30937. var j; // point iterator
  30938. // if single path in pathArray
  30939. if (pathArray.length < 2) {
  30940. var ar1 = [];
  30941. var ar2 = [];
  30942. for (i = 0; i < pathArray[0].length - offset; i++) {
  30943. ar1.push(pathArray[0][i]);
  30944. ar2.push(pathArray[0][i + offset]);
  30945. }
  30946. pathArray = [ar1, ar2];
  30947. }
  30948. // positions and horizontal distances (u)
  30949. var idc = 0;
  30950. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30951. var path;
  30952. var l;
  30953. minlg = pathArray[0].length;
  30954. var vectlg;
  30955. var dist;
  30956. for (p = 0; p < pathArray.length; p++) {
  30957. uTotalDistance[p] = 0;
  30958. us[p] = [0];
  30959. path = pathArray[p];
  30960. l = path.length;
  30961. minlg = (minlg < l) ? minlg : l;
  30962. j = 0;
  30963. while (j < l) {
  30964. positions.push(path[j].x, path[j].y, path[j].z);
  30965. if (j > 0) {
  30966. vectlg = path[j].subtract(path[j - 1]).length();
  30967. dist = vectlg + uTotalDistance[p];
  30968. us[p].push(dist);
  30969. uTotalDistance[p] = dist;
  30970. }
  30971. j++;
  30972. }
  30973. if (closePath) {
  30974. j--;
  30975. positions.push(path[0].x, path[0].y, path[0].z);
  30976. vectlg = path[j].subtract(path[0]).length();
  30977. dist = vectlg + uTotalDistance[p];
  30978. us[p].push(dist);
  30979. uTotalDistance[p] = dist;
  30980. }
  30981. lg[p] = l + closePathCorr;
  30982. idx[p] = idc;
  30983. idc += (l + closePathCorr);
  30984. }
  30985. // vertical distances (v)
  30986. var path1;
  30987. var path2;
  30988. var vertex1 = null;
  30989. var vertex2 = null;
  30990. for (i = 0; i < minlg + closePathCorr; i++) {
  30991. vTotalDistance[i] = 0;
  30992. vs[i] = [0];
  30993. for (p = 0; p < pathArray.length - 1; p++) {
  30994. path1 = pathArray[p];
  30995. path2 = pathArray[p + 1];
  30996. if (i === minlg) {
  30997. vertex1 = path1[0];
  30998. vertex2 = path2[0];
  30999. }
  31000. else {
  31001. vertex1 = path1[i];
  31002. vertex2 = path2[i];
  31003. }
  31004. vectlg = vertex2.subtract(vertex1).length();
  31005. dist = vectlg + vTotalDistance[i];
  31006. vs[i].push(dist);
  31007. vTotalDistance[i] = dist;
  31008. }
  31009. if (closeArray && vertex2 && vertex1) {
  31010. path1 = pathArray[p];
  31011. path2 = pathArray[0];
  31012. if (i === minlg) {
  31013. vertex2 = path2[0];
  31014. }
  31015. vectlg = vertex2.subtract(vertex1).length();
  31016. dist = vectlg + vTotalDistance[i];
  31017. vTotalDistance[i] = dist;
  31018. }
  31019. }
  31020. // uvs
  31021. var u;
  31022. var v;
  31023. if (customUV) {
  31024. for (p = 0; p < customUV.length; p++) {
  31025. uvs.push(customUV[p].x, customUV[p].y);
  31026. }
  31027. }
  31028. else {
  31029. for (p = 0; p < pathArray.length; p++) {
  31030. for (i = 0; i < minlg + closePathCorr; i++) {
  31031. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  31032. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  31033. if (invertUV) {
  31034. uvs.push(v, u);
  31035. }
  31036. else {
  31037. uvs.push(u, v);
  31038. }
  31039. }
  31040. }
  31041. }
  31042. // indices
  31043. p = 0; // path index
  31044. var pi = 0; // positions array index
  31045. var l1 = lg[p] - 1; // path1 length
  31046. var l2 = lg[p + 1] - 1; // path2 length
  31047. var min = (l1 < l2) ? l1 : l2; // current path stop index
  31048. var shft = idx[1] - idx[0]; // shift
  31049. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  31050. while (pi <= min && p < path1nb) {
  31051. // 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
  31052. indices.push(pi, pi + shft, pi + 1);
  31053. indices.push(pi + shft + 1, pi + 1, pi + shft);
  31054. pi += 1;
  31055. if (pi === min) {
  31056. p++;
  31057. if (p === lg.length - 1) {
  31058. shft = idx[0] - idx[p];
  31059. l1 = lg[p] - 1;
  31060. l2 = lg[0] - 1;
  31061. }
  31062. else {
  31063. shft = idx[p + 1] - idx[p];
  31064. l1 = lg[p] - 1;
  31065. l2 = lg[p + 1] - 1;
  31066. }
  31067. pi = idx[p];
  31068. min = (l1 < l2) ? l1 + pi : l2 + pi;
  31069. }
  31070. }
  31071. // normals
  31072. VertexData.ComputeNormals(positions, indices, normals);
  31073. if (closePath) {
  31074. var indexFirst = 0;
  31075. var indexLast = 0;
  31076. for (p = 0; p < pathArray.length; p++) {
  31077. indexFirst = idx[p] * 3;
  31078. if (p + 1 < pathArray.length) {
  31079. indexLast = (idx[p + 1] - 1) * 3;
  31080. }
  31081. else {
  31082. indexLast = normals.length - 3;
  31083. }
  31084. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  31085. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  31086. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  31087. normals[indexLast] = normals[indexFirst];
  31088. normals[indexLast + 1] = normals[indexFirst + 1];
  31089. normals[indexLast + 2] = normals[indexFirst + 2];
  31090. }
  31091. }
  31092. // sides
  31093. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31094. // Colors
  31095. var colors = null;
  31096. if (customColors) {
  31097. colors = new Float32Array(customColors.length * 4);
  31098. for (var c = 0; c < customColors.length; c++) {
  31099. colors[c * 4] = customColors[c].r;
  31100. colors[c * 4 + 1] = customColors[c].g;
  31101. colors[c * 4 + 2] = customColors[c].b;
  31102. colors[c * 4 + 3] = customColors[c].a;
  31103. }
  31104. }
  31105. // Result
  31106. var vertexData = new VertexData();
  31107. var positions32 = new Float32Array(positions);
  31108. var normals32 = new Float32Array(normals);
  31109. var uvs32 = new Float32Array(uvs);
  31110. vertexData.indices = indices;
  31111. vertexData.positions = positions32;
  31112. vertexData.normals = normals32;
  31113. vertexData.uvs = uvs32;
  31114. if (colors) {
  31115. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  31116. }
  31117. if (closePath) {
  31118. vertexData._idx = idx;
  31119. }
  31120. return vertexData;
  31121. };
  31122. /**
  31123. * Creates the VertexData of the Box.
  31124. */
  31125. VertexData.CreateBox = function (options) {
  31126. var normalsSource = [
  31127. new BABYLON.Vector3(0, 0, 1),
  31128. new BABYLON.Vector3(0, 0, -1),
  31129. new BABYLON.Vector3(1, 0, 0),
  31130. new BABYLON.Vector3(-1, 0, 0),
  31131. new BABYLON.Vector3(0, 1, 0),
  31132. new BABYLON.Vector3(0, -1, 0)
  31133. ];
  31134. var indices = [];
  31135. var positions = [];
  31136. var normals = [];
  31137. var uvs = [];
  31138. var width = options.width || options.size || 1;
  31139. var height = options.height || options.size || 1;
  31140. var depth = options.depth || options.size || 1;
  31141. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31142. var faceUV = options.faceUV || new Array(6);
  31143. var faceColors = options.faceColors;
  31144. var colors = [];
  31145. // default face colors and UV if undefined
  31146. for (var f = 0; f < 6; f++) {
  31147. if (faceUV[f] === undefined) {
  31148. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31149. }
  31150. if (faceColors && faceColors[f] === undefined) {
  31151. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31152. }
  31153. }
  31154. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31155. // Create each face in turn.
  31156. for (var index = 0; index < normalsSource.length; index++) {
  31157. var normal = normalsSource[index];
  31158. // Get two vectors perpendicular to the face normal and to each other.
  31159. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31160. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31161. // Six indices (two triangles) per face.
  31162. var verticesLength = positions.length / 3;
  31163. indices.push(verticesLength);
  31164. indices.push(verticesLength + 1);
  31165. indices.push(verticesLength + 2);
  31166. indices.push(verticesLength);
  31167. indices.push(verticesLength + 2);
  31168. indices.push(verticesLength + 3);
  31169. // Four vertices per face.
  31170. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31171. positions.push(vertex.x, vertex.y, vertex.z);
  31172. normals.push(normal.x, normal.y, normal.z);
  31173. uvs.push(faceUV[index].z, faceUV[index].w);
  31174. if (faceColors) {
  31175. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31176. }
  31177. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31178. positions.push(vertex.x, vertex.y, vertex.z);
  31179. normals.push(normal.x, normal.y, normal.z);
  31180. uvs.push(faceUV[index].x, faceUV[index].w);
  31181. if (faceColors) {
  31182. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31183. }
  31184. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31185. positions.push(vertex.x, vertex.y, vertex.z);
  31186. normals.push(normal.x, normal.y, normal.z);
  31187. uvs.push(faceUV[index].x, faceUV[index].y);
  31188. if (faceColors) {
  31189. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31190. }
  31191. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31192. positions.push(vertex.x, vertex.y, vertex.z);
  31193. normals.push(normal.x, normal.y, normal.z);
  31194. uvs.push(faceUV[index].z, faceUV[index].y);
  31195. if (faceColors) {
  31196. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31197. }
  31198. }
  31199. // sides
  31200. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31201. // Result
  31202. var vertexData = new VertexData();
  31203. vertexData.indices = indices;
  31204. vertexData.positions = positions;
  31205. vertexData.normals = normals;
  31206. vertexData.uvs = uvs;
  31207. if (faceColors) {
  31208. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31209. vertexData.colors = totalColors;
  31210. }
  31211. return vertexData;
  31212. };
  31213. /**
  31214. * Creates the VertexData of the Sphere.
  31215. */
  31216. VertexData.CreateSphere = function (options) {
  31217. var segments = options.segments || 32;
  31218. var diameterX = options.diameterX || options.diameter || 1;
  31219. var diameterY = options.diameterY || options.diameter || 1;
  31220. var diameterZ = options.diameterZ || options.diameter || 1;
  31221. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31222. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31223. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31224. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31225. var totalZRotationSteps = 2 + segments;
  31226. var totalYRotationSteps = 2 * totalZRotationSteps;
  31227. var indices = [];
  31228. var positions = [];
  31229. var normals = [];
  31230. var uvs = [];
  31231. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31232. var normalizedZ = zRotationStep / totalZRotationSteps;
  31233. var angleZ = normalizedZ * Math.PI * slice;
  31234. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31235. var normalizedY = yRotationStep / totalYRotationSteps;
  31236. var angleY = normalizedY * Math.PI * 2 * arc;
  31237. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31238. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31239. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31240. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31241. var vertex = complete.multiply(radius);
  31242. var normal = complete.divide(radius).normalize();
  31243. positions.push(vertex.x, vertex.y, vertex.z);
  31244. normals.push(normal.x, normal.y, normal.z);
  31245. uvs.push(normalizedY, normalizedZ);
  31246. }
  31247. if (zRotationStep > 0) {
  31248. var verticesCount = positions.length / 3;
  31249. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31250. indices.push((firstIndex));
  31251. indices.push((firstIndex + 1));
  31252. indices.push(firstIndex + totalYRotationSteps + 1);
  31253. indices.push((firstIndex + totalYRotationSteps + 1));
  31254. indices.push((firstIndex + 1));
  31255. indices.push((firstIndex + totalYRotationSteps + 2));
  31256. }
  31257. }
  31258. }
  31259. // Sides
  31260. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31261. // Result
  31262. var vertexData = new VertexData();
  31263. vertexData.indices = indices;
  31264. vertexData.positions = positions;
  31265. vertexData.normals = normals;
  31266. vertexData.uvs = uvs;
  31267. return vertexData;
  31268. };
  31269. /**
  31270. * Creates the VertexData of the Cylinder or Cone.
  31271. */
  31272. VertexData.CreateCylinder = function (options) {
  31273. var height = options.height || 2;
  31274. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31275. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31276. var tessellation = options.tessellation || 24;
  31277. var subdivisions = options.subdivisions || 1;
  31278. var hasRings = options.hasRings ? true : false;
  31279. var enclose = options.enclose ? true : false;
  31280. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31281. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31282. var faceUV = options.faceUV || new Array(3);
  31283. var faceColors = options.faceColors;
  31284. // default face colors and UV if undefined
  31285. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31286. var ringNb = (hasRings) ? subdivisions : 1;
  31287. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31288. var f;
  31289. for (f = 0; f < surfaceNb; f++) {
  31290. if (faceColors && faceColors[f] === undefined) {
  31291. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31292. }
  31293. }
  31294. for (f = 0; f < surfaceNb; f++) {
  31295. if (faceUV && faceUV[f] === undefined) {
  31296. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31297. }
  31298. }
  31299. var indices = new Array();
  31300. var positions = new Array();
  31301. var normals = new Array();
  31302. var uvs = new Array();
  31303. var colors = new Array();
  31304. var angle_step = Math.PI * 2 * arc / tessellation;
  31305. var angle;
  31306. var h;
  31307. var radius;
  31308. var tan = (diameterBottom - diameterTop) / 2 / height;
  31309. var ringVertex = BABYLON.Vector3.Zero();
  31310. var ringNormal = BABYLON.Vector3.Zero();
  31311. var ringFirstVertex = BABYLON.Vector3.Zero();
  31312. var ringFirstNormal = BABYLON.Vector3.Zero();
  31313. var quadNormal = BABYLON.Vector3.Zero();
  31314. var Y = BABYLON.Axis.Y;
  31315. // positions, normals, uvs
  31316. var i;
  31317. var j;
  31318. var r;
  31319. var ringIdx = 1;
  31320. var s = 1; // surface index
  31321. var cs = 0;
  31322. var v = 0;
  31323. for (i = 0; i <= subdivisions; i++) {
  31324. h = i / subdivisions;
  31325. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31326. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31327. for (r = 0; r < ringIdx; r++) {
  31328. if (hasRings) {
  31329. s += r;
  31330. }
  31331. if (enclose) {
  31332. s += 2 * r;
  31333. }
  31334. for (j = 0; j <= tessellation; j++) {
  31335. angle = j * angle_step;
  31336. // position
  31337. ringVertex.x = Math.cos(-angle) * radius;
  31338. ringVertex.y = -height / 2 + h * height;
  31339. ringVertex.z = Math.sin(-angle) * radius;
  31340. // normal
  31341. if (diameterTop === 0 && i === subdivisions) {
  31342. // if no top cap, reuse former normals
  31343. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31344. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31345. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31346. }
  31347. else {
  31348. ringNormal.x = ringVertex.x;
  31349. ringNormal.z = ringVertex.z;
  31350. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31351. ringNormal.normalize();
  31352. }
  31353. // keep first ring vertex values for enclose
  31354. if (j === 0) {
  31355. ringFirstVertex.copyFrom(ringVertex);
  31356. ringFirstNormal.copyFrom(ringNormal);
  31357. }
  31358. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31359. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31360. if (hasRings) {
  31361. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31362. }
  31363. else {
  31364. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31365. }
  31366. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31367. if (faceColors) {
  31368. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31369. }
  31370. }
  31371. // if enclose, add four vertices and their dedicated normals
  31372. if (arc !== 1 && enclose) {
  31373. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31374. positions.push(0, ringVertex.y, 0);
  31375. positions.push(0, ringVertex.y, 0);
  31376. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31377. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31378. quadNormal.normalize();
  31379. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31380. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31381. quadNormal.normalize();
  31382. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31383. if (hasRings) {
  31384. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31385. }
  31386. else {
  31387. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31388. }
  31389. uvs.push(faceUV[s + 1].x, v);
  31390. uvs.push(faceUV[s + 1].z, v);
  31391. if (hasRings) {
  31392. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31393. }
  31394. else {
  31395. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31396. }
  31397. uvs.push(faceUV[s + 2].x, v);
  31398. uvs.push(faceUV[s + 2].z, v);
  31399. if (faceColors) {
  31400. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31401. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31402. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31403. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31404. }
  31405. }
  31406. if (cs !== s) {
  31407. cs = s;
  31408. }
  31409. }
  31410. }
  31411. // indices
  31412. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31413. var s;
  31414. i = 0;
  31415. for (s = 0; s < subdivisions; s++) {
  31416. var i0 = 0;
  31417. var i1 = 0;
  31418. var i2 = 0;
  31419. var i3 = 0;
  31420. for (j = 0; j < tessellation; j++) {
  31421. i0 = i * (e + 1) + j;
  31422. i1 = (i + 1) * (e + 1) + j;
  31423. i2 = i * (e + 1) + (j + 1);
  31424. i3 = (i + 1) * (e + 1) + (j + 1);
  31425. indices.push(i0, i1, i2);
  31426. indices.push(i3, i2, i1);
  31427. }
  31428. if (arc !== 1 && enclose) {
  31429. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31430. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31431. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31432. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31433. }
  31434. i = (hasRings) ? (i + 2) : (i + 1);
  31435. }
  31436. // Caps
  31437. var createCylinderCap = function (isTop) {
  31438. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31439. if (radius === 0) {
  31440. return;
  31441. }
  31442. // Cap positions, normals & uvs
  31443. var angle;
  31444. var circleVector;
  31445. var i;
  31446. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31447. var c = null;
  31448. if (faceColors) {
  31449. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31450. }
  31451. // cap center
  31452. var vbase = positions.length / 3;
  31453. var offset = isTop ? height / 2 : -height / 2;
  31454. var center = new BABYLON.Vector3(0, offset, 0);
  31455. positions.push(center.x, center.y, center.z);
  31456. normals.push(0, isTop ? 1 : -1, 0);
  31457. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31458. if (c) {
  31459. colors.push(c.r, c.g, c.b, c.a);
  31460. }
  31461. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31462. for (i = 0; i <= tessellation; i++) {
  31463. angle = Math.PI * 2 * i * arc / tessellation;
  31464. var cos = Math.cos(-angle);
  31465. var sin = Math.sin(-angle);
  31466. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31467. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31468. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31469. normals.push(0, isTop ? 1 : -1, 0);
  31470. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31471. if (c) {
  31472. colors.push(c.r, c.g, c.b, c.a);
  31473. }
  31474. }
  31475. // Cap indices
  31476. for (i = 0; i < tessellation; i++) {
  31477. if (!isTop) {
  31478. indices.push(vbase);
  31479. indices.push(vbase + (i + 1));
  31480. indices.push(vbase + (i + 2));
  31481. }
  31482. else {
  31483. indices.push(vbase);
  31484. indices.push(vbase + (i + 2));
  31485. indices.push(vbase + (i + 1));
  31486. }
  31487. }
  31488. };
  31489. // add caps to geometry
  31490. createCylinderCap(false);
  31491. createCylinderCap(true);
  31492. // Sides
  31493. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31494. var vertexData = new VertexData();
  31495. vertexData.indices = indices;
  31496. vertexData.positions = positions;
  31497. vertexData.normals = normals;
  31498. vertexData.uvs = uvs;
  31499. if (faceColors) {
  31500. vertexData.colors = colors;
  31501. }
  31502. return vertexData;
  31503. };
  31504. /**
  31505. * Creates the VertexData of the Torus.
  31506. */
  31507. VertexData.CreateTorus = function (options) {
  31508. var indices = [];
  31509. var positions = [];
  31510. var normals = [];
  31511. var uvs = [];
  31512. var diameter = options.diameter || 1;
  31513. var thickness = options.thickness || 0.5;
  31514. var tessellation = options.tessellation || 16;
  31515. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31516. var stride = tessellation + 1;
  31517. for (var i = 0; i <= tessellation; i++) {
  31518. var u = i / tessellation;
  31519. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31520. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31521. for (var j = 0; j <= tessellation; j++) {
  31522. var v = 1 - j / tessellation;
  31523. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31524. var dx = Math.cos(innerAngle);
  31525. var dy = Math.sin(innerAngle);
  31526. // Create a vertex.
  31527. var normal = new BABYLON.Vector3(dx, dy, 0);
  31528. var position = normal.scale(thickness / 2);
  31529. var textureCoordinate = new BABYLON.Vector2(u, v);
  31530. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31531. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31532. positions.push(position.x, position.y, position.z);
  31533. normals.push(normal.x, normal.y, normal.z);
  31534. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31535. // And create indices for two triangles.
  31536. var nextI = (i + 1) % stride;
  31537. var nextJ = (j + 1) % stride;
  31538. indices.push(i * stride + j);
  31539. indices.push(i * stride + nextJ);
  31540. indices.push(nextI * stride + j);
  31541. indices.push(i * stride + nextJ);
  31542. indices.push(nextI * stride + nextJ);
  31543. indices.push(nextI * stride + j);
  31544. }
  31545. }
  31546. // Sides
  31547. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31548. // Result
  31549. var vertexData = new VertexData();
  31550. vertexData.indices = indices;
  31551. vertexData.positions = positions;
  31552. vertexData.normals = normals;
  31553. vertexData.uvs = uvs;
  31554. return vertexData;
  31555. };
  31556. /**
  31557. * Creates the VertexData of the LineSystem.
  31558. */
  31559. VertexData.CreateLineSystem = function (options) {
  31560. var indices = [];
  31561. var positions = [];
  31562. var lines = options.lines;
  31563. var colors = options.colors;
  31564. var vertexColors = [];
  31565. var idx = 0;
  31566. for (var l = 0; l < lines.length; l++) {
  31567. var points = lines[l];
  31568. for (var index = 0; index < points.length; index++) {
  31569. positions.push(points[index].x, points[index].y, points[index].z);
  31570. if (colors) {
  31571. var color = colors[l];
  31572. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  31573. }
  31574. if (index > 0) {
  31575. indices.push(idx - 1);
  31576. indices.push(idx);
  31577. }
  31578. idx++;
  31579. }
  31580. }
  31581. var vertexData = new VertexData();
  31582. vertexData.indices = indices;
  31583. vertexData.positions = positions;
  31584. if (colors) {
  31585. vertexData.colors = vertexColors;
  31586. }
  31587. return vertexData;
  31588. };
  31589. /**
  31590. * Create the VertexData of the DashedLines.
  31591. */
  31592. VertexData.CreateDashedLines = function (options) {
  31593. var dashSize = options.dashSize || 3;
  31594. var gapSize = options.gapSize || 1;
  31595. var dashNb = options.dashNb || 200;
  31596. var points = options.points;
  31597. var positions = new Array();
  31598. var indices = new Array();
  31599. var curvect = BABYLON.Vector3.Zero();
  31600. var lg = 0;
  31601. var nb = 0;
  31602. var shft = 0;
  31603. var dashshft = 0;
  31604. var curshft = 0;
  31605. var idx = 0;
  31606. var i = 0;
  31607. for (i = 0; i < points.length - 1; i++) {
  31608. points[i + 1].subtractToRef(points[i], curvect);
  31609. lg += curvect.length();
  31610. }
  31611. shft = lg / dashNb;
  31612. dashshft = dashSize * shft / (dashSize + gapSize);
  31613. for (i = 0; i < points.length - 1; i++) {
  31614. points[i + 1].subtractToRef(points[i], curvect);
  31615. nb = Math.floor(curvect.length() / shft);
  31616. curvect.normalize();
  31617. for (var j = 0; j < nb; j++) {
  31618. curshft = shft * j;
  31619. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31620. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31621. indices.push(idx, idx + 1);
  31622. idx += 2;
  31623. }
  31624. }
  31625. // Result
  31626. var vertexData = new VertexData();
  31627. vertexData.positions = positions;
  31628. vertexData.indices = indices;
  31629. return vertexData;
  31630. };
  31631. /**
  31632. * Creates the VertexData of the Ground.
  31633. */
  31634. VertexData.CreateGround = function (options) {
  31635. var indices = [];
  31636. var positions = [];
  31637. var normals = [];
  31638. var uvs = [];
  31639. var row, col;
  31640. var width = options.width || 1;
  31641. var height = options.height || 1;
  31642. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31643. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31644. for (row = 0; row <= subdivisionsY; row++) {
  31645. for (col = 0; col <= subdivisionsX; col++) {
  31646. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31647. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31648. positions.push(position.x, position.y, position.z);
  31649. normals.push(normal.x, normal.y, normal.z);
  31650. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  31651. }
  31652. }
  31653. for (row = 0; row < subdivisionsY; row++) {
  31654. for (col = 0; col < subdivisionsX; col++) {
  31655. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31656. indices.push(col + 1 + row * (subdivisionsX + 1));
  31657. indices.push(col + row * (subdivisionsX + 1));
  31658. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31659. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31660. indices.push(col + row * (subdivisionsX + 1));
  31661. }
  31662. }
  31663. // Result
  31664. var vertexData = new VertexData();
  31665. vertexData.indices = indices;
  31666. vertexData.positions = positions;
  31667. vertexData.normals = normals;
  31668. vertexData.uvs = uvs;
  31669. return vertexData;
  31670. };
  31671. /**
  31672. * Creates the VertexData of the TiledGround.
  31673. */
  31674. VertexData.CreateTiledGround = function (options) {
  31675. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  31676. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  31677. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  31678. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  31679. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31680. var precision = options.precision || { w: 1, h: 1 };
  31681. var indices = new Array();
  31682. var positions = new Array();
  31683. var normals = new Array();
  31684. var uvs = new Array();
  31685. var row, col, tileRow, tileCol;
  31686. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31687. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31688. precision.w = (precision.w < 1) ? 1 : precision.w;
  31689. precision.h = (precision.h < 1) ? 1 : precision.h;
  31690. var tileSize = {
  31691. 'w': (xmax - xmin) / subdivisions.w,
  31692. 'h': (zmax - zmin) / subdivisions.h
  31693. };
  31694. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31695. // Indices
  31696. var base = positions.length / 3;
  31697. var rowLength = precision.w + 1;
  31698. for (row = 0; row < precision.h; row++) {
  31699. for (col = 0; col < precision.w; col++) {
  31700. var square = [
  31701. base + col + row * rowLength,
  31702. base + (col + 1) + row * rowLength,
  31703. base + (col + 1) + (row + 1) * rowLength,
  31704. base + col + (row + 1) * rowLength
  31705. ];
  31706. indices.push(square[1]);
  31707. indices.push(square[2]);
  31708. indices.push(square[3]);
  31709. indices.push(square[0]);
  31710. indices.push(square[1]);
  31711. indices.push(square[3]);
  31712. }
  31713. }
  31714. // Position, normals and uvs
  31715. var position = BABYLON.Vector3.Zero();
  31716. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31717. for (row = 0; row <= precision.h; row++) {
  31718. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31719. for (col = 0; col <= precision.w; col++) {
  31720. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31721. position.y = 0;
  31722. positions.push(position.x, position.y, position.z);
  31723. normals.push(normal.x, normal.y, normal.z);
  31724. uvs.push(col / precision.w, row / precision.h);
  31725. }
  31726. }
  31727. }
  31728. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31729. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31730. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31731. }
  31732. }
  31733. // Result
  31734. var vertexData = new VertexData();
  31735. vertexData.indices = indices;
  31736. vertexData.positions = positions;
  31737. vertexData.normals = normals;
  31738. vertexData.uvs = uvs;
  31739. return vertexData;
  31740. };
  31741. /**
  31742. * Creates the VertexData of the Ground designed from a heightmap.
  31743. */
  31744. VertexData.CreateGroundFromHeightMap = function (options) {
  31745. var indices = [];
  31746. var positions = [];
  31747. var normals = [];
  31748. var uvs = [];
  31749. var row, col;
  31750. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  31751. // Vertices
  31752. for (row = 0; row <= options.subdivisions; row++) {
  31753. for (col = 0; col <= options.subdivisions; col++) {
  31754. 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));
  31755. // Compute height
  31756. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31757. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31758. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31759. var r = options.buffer[pos] / 255.0;
  31760. var g = options.buffer[pos + 1] / 255.0;
  31761. var b = options.buffer[pos + 2] / 255.0;
  31762. var gradient = r * filter.r + g * filter.g + b * filter.b;
  31763. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31764. // Add vertex
  31765. positions.push(position.x, position.y, position.z);
  31766. normals.push(0, 0, 0);
  31767. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31768. }
  31769. }
  31770. // Indices
  31771. for (row = 0; row < options.subdivisions; row++) {
  31772. for (col = 0; col < options.subdivisions; col++) {
  31773. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31774. indices.push(col + 1 + row * (options.subdivisions + 1));
  31775. indices.push(col + row * (options.subdivisions + 1));
  31776. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31777. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31778. indices.push(col + row * (options.subdivisions + 1));
  31779. }
  31780. }
  31781. // Normals
  31782. VertexData.ComputeNormals(positions, indices, normals);
  31783. // Result
  31784. var vertexData = new VertexData();
  31785. vertexData.indices = indices;
  31786. vertexData.positions = positions;
  31787. vertexData.normals = normals;
  31788. vertexData.uvs = uvs;
  31789. return vertexData;
  31790. };
  31791. /**
  31792. * Creates the VertexData of the Plane.
  31793. */
  31794. VertexData.CreatePlane = function (options) {
  31795. var indices = [];
  31796. var positions = [];
  31797. var normals = [];
  31798. var uvs = [];
  31799. var width = options.width || options.size || 1;
  31800. var height = options.height || options.size || 1;
  31801. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31802. // Vertices
  31803. var halfWidth = width / 2.0;
  31804. var halfHeight = height / 2.0;
  31805. positions.push(-halfWidth, -halfHeight, 0);
  31806. normals.push(0, 0, -1.0);
  31807. uvs.push(0.0, 0.0);
  31808. positions.push(halfWidth, -halfHeight, 0);
  31809. normals.push(0, 0, -1.0);
  31810. uvs.push(1.0, 0.0);
  31811. positions.push(halfWidth, halfHeight, 0);
  31812. normals.push(0, 0, -1.0);
  31813. uvs.push(1.0, 1.0);
  31814. positions.push(-halfWidth, halfHeight, 0);
  31815. normals.push(0, 0, -1.0);
  31816. uvs.push(0.0, 1.0);
  31817. // Indices
  31818. indices.push(0);
  31819. indices.push(1);
  31820. indices.push(2);
  31821. indices.push(0);
  31822. indices.push(2);
  31823. indices.push(3);
  31824. // Sides
  31825. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31826. // Result
  31827. var vertexData = new VertexData();
  31828. vertexData.indices = indices;
  31829. vertexData.positions = positions;
  31830. vertexData.normals = normals;
  31831. vertexData.uvs = uvs;
  31832. return vertexData;
  31833. };
  31834. /**
  31835. * Creates the VertexData of the Disc or regular Polygon.
  31836. */
  31837. VertexData.CreateDisc = function (options) {
  31838. var positions = new Array();
  31839. var indices = new Array();
  31840. var normals = new Array();
  31841. var uvs = new Array();
  31842. var radius = options.radius || 0.5;
  31843. var tessellation = options.tessellation || 64;
  31844. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31845. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31846. // positions and uvs
  31847. positions.push(0, 0, 0); // disc center first
  31848. uvs.push(0.5, 0.5);
  31849. var theta = Math.PI * 2 * arc;
  31850. var step = theta / tessellation;
  31851. for (var a = 0; a < theta; a += step) {
  31852. var x = Math.cos(a);
  31853. var y = Math.sin(a);
  31854. var u = (x + 1) / 2;
  31855. var v = (1 - y) / 2;
  31856. positions.push(radius * x, radius * y, 0);
  31857. uvs.push(u, v);
  31858. }
  31859. if (arc === 1) {
  31860. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31861. uvs.push(uvs[2], uvs[3]);
  31862. }
  31863. //indices
  31864. var vertexNb = positions.length / 3;
  31865. for (var i = 1; i < vertexNb - 1; i++) {
  31866. indices.push(i + 1, 0, i);
  31867. }
  31868. // result
  31869. VertexData.ComputeNormals(positions, indices, normals);
  31870. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31871. var vertexData = new VertexData();
  31872. vertexData.indices = indices;
  31873. vertexData.positions = positions;
  31874. vertexData.normals = normals;
  31875. vertexData.uvs = uvs;
  31876. return vertexData;
  31877. };
  31878. /**
  31879. * Re-creates the VertexData of the Polygon for sideOrientation.
  31880. */
  31881. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31882. var faceUV = fUV || new Array(3);
  31883. var faceColors = fColors;
  31884. var colors = [];
  31885. // default face colors and UV if undefined
  31886. for (var f = 0; f < 3; f++) {
  31887. if (faceUV[f] === undefined) {
  31888. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31889. }
  31890. if (faceColors && faceColors[f] === undefined) {
  31891. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31892. }
  31893. }
  31894. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31895. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31896. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31897. var indices = polygon.getIndices();
  31898. // set face colours and textures
  31899. var idx = 0;
  31900. var face = 0;
  31901. for (var index = 0; index < normals.length; index += 3) {
  31902. //Edge Face no. 1
  31903. if (Math.abs(normals[index + 1]) < 0.001) {
  31904. face = 1;
  31905. }
  31906. //Top Face no. 0
  31907. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31908. face = 0;
  31909. }
  31910. //Bottom Face no. 2
  31911. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31912. face = 2;
  31913. }
  31914. idx = index / 3;
  31915. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31916. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31917. if (faceColors) {
  31918. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31919. }
  31920. }
  31921. // sides
  31922. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31923. // Result
  31924. var vertexData = new VertexData();
  31925. vertexData.indices = indices;
  31926. vertexData.positions = positions;
  31927. vertexData.normals = normals;
  31928. vertexData.uvs = uvs;
  31929. if (faceColors) {
  31930. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31931. vertexData.colors = totalColors;
  31932. }
  31933. return vertexData;
  31934. };
  31935. /**
  31936. * Creates the VertexData of the IcoSphere.
  31937. */
  31938. VertexData.CreateIcoSphere = function (options) {
  31939. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31940. var radius = options.radius || 1;
  31941. var flat = (options.flat === undefined) ? true : options.flat;
  31942. var subdivisions = options.subdivisions || 4;
  31943. var radiusX = options.radiusX || radius;
  31944. var radiusY = options.radiusY || radius;
  31945. var radiusZ = options.radiusZ || radius;
  31946. var t = (1 + Math.sqrt(5)) / 2;
  31947. // 12 vertex x,y,z
  31948. var ico_vertices = [
  31949. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31950. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31951. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31952. ];
  31953. // index of 3 vertex makes a face of icopshere
  31954. var ico_indices = [
  31955. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31956. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31957. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31958. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31959. ];
  31960. // vertex for uv have aliased position, not for UV
  31961. var vertices_unalias_id = [
  31962. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31963. // vertex alias
  31964. 0,
  31965. 2,
  31966. 3,
  31967. 3,
  31968. 3,
  31969. 4,
  31970. 7,
  31971. 8,
  31972. 9,
  31973. 9,
  31974. 10,
  31975. 11 // 23: B + 12
  31976. ];
  31977. // uv as integer step (not pixels !)
  31978. var ico_vertexuv = [
  31979. 5, 1, 3, 1, 6, 4, 0, 0,
  31980. 5, 3, 4, 2, 2, 2, 4, 0,
  31981. 2, 0, 1, 1, 6, 0, 6, 2,
  31982. // vertex alias (for same vertex on different faces)
  31983. 0, 4,
  31984. 3, 3,
  31985. 4, 4,
  31986. 3, 1,
  31987. 4, 2,
  31988. 4, 4,
  31989. 0, 2,
  31990. 1, 1,
  31991. 2, 2,
  31992. 3, 3,
  31993. 1, 3,
  31994. 2, 4 // 23: B + 12
  31995. ];
  31996. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31997. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31998. // First island of uv mapping
  31999. // v = 4h 3+ 2
  32000. // v = 3h 9+ 4
  32001. // v = 2h 9+ 5 B
  32002. // v = 1h 9 1 0
  32003. // v = 0h 3 8 7 A
  32004. // u = 0 1 2 3 4 5 6 *a
  32005. // Second island of uv mapping
  32006. // v = 4h 0+ B+ 4+
  32007. // v = 3h A+ 2+
  32008. // v = 2h 7+ 6 3+
  32009. // v = 1h 8+ 3+
  32010. // v = 0h
  32011. // u = 0 1 2 3 4 5 6 *a
  32012. // Face layout on texture UV mapping
  32013. // ============
  32014. // \ 4 /\ 16 / ======
  32015. // \ / \ / /\ 11 /
  32016. // \/ 7 \/ / \ /
  32017. // ======= / 10 \/
  32018. // /\ 17 /\ =======
  32019. // / \ / \ \ 15 /\
  32020. // / 8 \/ 12 \ \ / \
  32021. // ============ \/ 6 \
  32022. // \ 18 /\ ============
  32023. // \ / \ \ 5 /\ 0 /
  32024. // \/ 13 \ \ / \ /
  32025. // ======= \/ 1 \/
  32026. // =============
  32027. // /\ 19 /\ 2 /\
  32028. // / \ / \ / \
  32029. // / 14 \/ 9 \/ 3 \
  32030. // ===================
  32031. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  32032. var ustep = 138 / 1024;
  32033. var vstep = 239 / 1024;
  32034. var uoffset = 60 / 1024;
  32035. var voffset = 26 / 1024;
  32036. // Second island should have margin, not to touch the first island
  32037. // avoid any borderline artefact in pixel rounding
  32038. var island_u_offset = -40 / 1024;
  32039. var island_v_offset = +20 / 1024;
  32040. // face is either island 0 or 1 :
  32041. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  32042. var island = [
  32043. 0, 0, 0, 0, 1,
  32044. 0, 0, 1, 1, 0,
  32045. 0, 0, 1, 1, 0,
  32046. 0, 1, 1, 1, 0 // 15 - 19
  32047. ];
  32048. var indices = new Array();
  32049. var positions = new Array();
  32050. var normals = new Array();
  32051. var uvs = new Array();
  32052. var current_indice = 0;
  32053. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  32054. var face_vertex_pos = new Array(3);
  32055. var face_vertex_uv = new Array(3);
  32056. var v012;
  32057. for (v012 = 0; v012 < 3; v012++) {
  32058. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  32059. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  32060. }
  32061. // create all with normals
  32062. for (var face = 0; face < 20; face++) {
  32063. // 3 vertex per face
  32064. for (v012 = 0; v012 < 3; v012++) {
  32065. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  32066. var v_id = ico_indices[3 * face + v012];
  32067. // vertex have 3D position (x,y,z)
  32068. 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]);
  32069. // Normalize to get normal, then scale to radius
  32070. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  32071. // uv Coordinates from vertex ID
  32072. 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);
  32073. }
  32074. // Subdivide the face (interpolate pos, norm, uv)
  32075. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  32076. // - norm is linear interpolation of vertex corner normal
  32077. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  32078. // - uv is linear interpolation
  32079. //
  32080. // Topology is as below for sub-divide by 2
  32081. // vertex shown as v0,v1,v2
  32082. // interp index is i1 to progress in range [v0,v1[
  32083. // interp index is i2 to progress in range [v0,v2[
  32084. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  32085. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32086. //
  32087. //
  32088. // i2 v2
  32089. // ^ ^
  32090. // / / \
  32091. // / / \
  32092. // / / \
  32093. // / / (0,1) \
  32094. // / #---------\
  32095. // / / \ (0,0)'/ \
  32096. // / / \ / \
  32097. // / / \ / \
  32098. // / / (0,0) \ / (1,0) \
  32099. // / #---------#---------\
  32100. // v0 v1
  32101. //
  32102. // --------------------> i1
  32103. //
  32104. // interp of (i1,i2):
  32105. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  32106. // along i1 : lerp(x0,x1, i1/(S-i2))
  32107. //
  32108. // centroid of triangle is needed to get help normal computation
  32109. // (c1,c2) are used for centroid location
  32110. var interp_vertex = function (i1, i2, c1, c2) {
  32111. // vertex is interpolated from
  32112. // - face_vertex_pos[0..2]
  32113. // - face_vertex_uv[0..2]
  32114. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  32115. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  32116. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  32117. pos_interp.normalize();
  32118. var vertex_normal;
  32119. if (flat) {
  32120. // in flat mode, recalculate normal as face centroid normal
  32121. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32122. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32123. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32124. }
  32125. else {
  32126. // in smooth mode, recalculate normal from each single vertex position
  32127. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32128. }
  32129. // Vertex normal need correction due to X,Y,Z radius scaling
  32130. vertex_normal.x /= radiusX;
  32131. vertex_normal.y /= radiusY;
  32132. vertex_normal.z /= radiusZ;
  32133. vertex_normal.normalize();
  32134. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32135. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32136. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32137. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32138. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32139. uvs.push(uv_interp.x, uv_interp.y);
  32140. // push each vertex has member of a face
  32141. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32142. indices.push(current_indice);
  32143. current_indice++;
  32144. };
  32145. for (var i2 = 0; i2 < subdivisions; i2++) {
  32146. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32147. // face : (i1,i2) for /\ :
  32148. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32149. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32150. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32151. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32152. if (i1 + i2 + 1 < subdivisions) {
  32153. // face : (i1,i2)' for \/ :
  32154. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32155. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32156. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32157. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32158. }
  32159. }
  32160. }
  32161. }
  32162. // Sides
  32163. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32164. // Result
  32165. var vertexData = new VertexData();
  32166. vertexData.indices = indices;
  32167. vertexData.positions = positions;
  32168. vertexData.normals = normals;
  32169. vertexData.uvs = uvs;
  32170. return vertexData;
  32171. };
  32172. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32173. /**
  32174. * Creates the VertexData of the Polyhedron.
  32175. */
  32176. VertexData.CreatePolyhedron = function (options) {
  32177. // provided polyhedron types :
  32178. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32179. // 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)
  32180. var polyhedra = [];
  32181. 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]] };
  32182. 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]] };
  32183. polyhedra[2] = {
  32184. 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]],
  32185. 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]]
  32186. };
  32187. polyhedra[3] = {
  32188. 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]],
  32189. 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]]
  32190. };
  32191. polyhedra[4] = {
  32192. 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]],
  32193. 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]]
  32194. };
  32195. 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]] };
  32196. 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]] };
  32197. 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]] };
  32198. 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]] };
  32199. 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]] };
  32200. 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]] };
  32201. 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]] };
  32202. 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]] };
  32203. 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]] };
  32204. polyhedra[14] = {
  32205. 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]],
  32206. 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]]
  32207. };
  32208. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32209. var size = options.size;
  32210. var sizeX = options.sizeX || size || 1;
  32211. var sizeY = options.sizeY || size || 1;
  32212. var sizeZ = options.sizeZ || size || 1;
  32213. var data = options.custom || polyhedra[type];
  32214. var nbfaces = data.face.length;
  32215. var faceUV = options.faceUV || new Array(nbfaces);
  32216. var faceColors = options.faceColors;
  32217. var flat = (options.flat === undefined) ? true : options.flat;
  32218. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32219. var positions = new Array();
  32220. var indices = new Array();
  32221. var normals = new Array();
  32222. var uvs = new Array();
  32223. var colors = new Array();
  32224. var index = 0;
  32225. var faceIdx = 0; // face cursor in the array "indexes"
  32226. var indexes = new Array();
  32227. var i = 0;
  32228. var f = 0;
  32229. var u, v, ang, x, y, tmp;
  32230. // default face colors and UV if undefined
  32231. if (flat) {
  32232. for (f = 0; f < nbfaces; f++) {
  32233. if (faceColors && faceColors[f] === undefined) {
  32234. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32235. }
  32236. if (faceUV && faceUV[f] === undefined) {
  32237. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32238. }
  32239. }
  32240. }
  32241. if (!flat) {
  32242. for (i = 0; i < data.vertex.length; i++) {
  32243. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32244. uvs.push(0, 0);
  32245. }
  32246. for (f = 0; f < nbfaces; f++) {
  32247. for (i = 0; i < data.face[f].length - 2; i++) {
  32248. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32249. }
  32250. }
  32251. }
  32252. else {
  32253. for (f = 0; f < nbfaces; f++) {
  32254. var fl = data.face[f].length; // number of vertices of the current face
  32255. ang = 2 * Math.PI / fl;
  32256. x = 0.5 * Math.tan(ang / 2);
  32257. y = 0.5;
  32258. // positions, uvs, colors
  32259. for (i = 0; i < fl; i++) {
  32260. // positions
  32261. 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);
  32262. indexes.push(index);
  32263. index++;
  32264. // uvs
  32265. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32266. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32267. uvs.push(u, v);
  32268. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32269. y = x * Math.sin(ang) + y * Math.cos(ang);
  32270. x = tmp;
  32271. // colors
  32272. if (faceColors) {
  32273. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32274. }
  32275. }
  32276. // indices from indexes
  32277. for (i = 0; i < fl - 2; i++) {
  32278. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32279. }
  32280. faceIdx += fl;
  32281. }
  32282. }
  32283. VertexData.ComputeNormals(positions, indices, normals);
  32284. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32285. var vertexData = new VertexData();
  32286. vertexData.positions = positions;
  32287. vertexData.indices = indices;
  32288. vertexData.normals = normals;
  32289. vertexData.uvs = uvs;
  32290. if (faceColors && flat) {
  32291. vertexData.colors = colors;
  32292. }
  32293. return vertexData;
  32294. };
  32295. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32296. /**
  32297. * Creates the VertexData of the Torus Knot.
  32298. */
  32299. VertexData.CreateTorusKnot = function (options) {
  32300. var indices = new Array();
  32301. var positions = new Array();
  32302. var normals = new Array();
  32303. var uvs = new Array();
  32304. var radius = options.radius || 2;
  32305. var tube = options.tube || 0.5;
  32306. var radialSegments = options.radialSegments || 32;
  32307. var tubularSegments = options.tubularSegments || 32;
  32308. var p = options.p || 2;
  32309. var q = options.q || 3;
  32310. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32311. // Helper
  32312. var getPos = function (angle) {
  32313. var cu = Math.cos(angle);
  32314. var su = Math.sin(angle);
  32315. var quOverP = q / p * angle;
  32316. var cs = Math.cos(quOverP);
  32317. var tx = radius * (2 + cs) * 0.5 * cu;
  32318. var ty = radius * (2 + cs) * su * 0.5;
  32319. var tz = radius * Math.sin(quOverP) * 0.5;
  32320. return new BABYLON.Vector3(tx, ty, tz);
  32321. };
  32322. // Vertices
  32323. var i;
  32324. var j;
  32325. for (i = 0; i <= radialSegments; i++) {
  32326. var modI = i % radialSegments;
  32327. var u = modI / radialSegments * 2 * p * Math.PI;
  32328. var p1 = getPos(u);
  32329. var p2 = getPos(u + 0.01);
  32330. var tang = p2.subtract(p1);
  32331. var n = p2.add(p1);
  32332. var bitan = BABYLON.Vector3.Cross(tang, n);
  32333. n = BABYLON.Vector3.Cross(bitan, tang);
  32334. bitan.normalize();
  32335. n.normalize();
  32336. for (j = 0; j < tubularSegments; j++) {
  32337. var modJ = j % tubularSegments;
  32338. var v = modJ / tubularSegments * 2 * Math.PI;
  32339. var cx = -tube * Math.cos(v);
  32340. var cy = tube * Math.sin(v);
  32341. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32342. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32343. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32344. uvs.push(i / radialSegments);
  32345. uvs.push(j / tubularSegments);
  32346. }
  32347. }
  32348. for (i = 0; i < radialSegments; i++) {
  32349. for (j = 0; j < tubularSegments; j++) {
  32350. var jNext = (j + 1) % tubularSegments;
  32351. var a = i * tubularSegments + j;
  32352. var b = (i + 1) * tubularSegments + j;
  32353. var c = (i + 1) * tubularSegments + jNext;
  32354. var d = i * tubularSegments + jNext;
  32355. indices.push(d);
  32356. indices.push(b);
  32357. indices.push(a);
  32358. indices.push(d);
  32359. indices.push(c);
  32360. indices.push(b);
  32361. }
  32362. }
  32363. // Normals
  32364. VertexData.ComputeNormals(positions, indices, normals);
  32365. // Sides
  32366. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32367. // Result
  32368. var vertexData = new VertexData();
  32369. vertexData.indices = indices;
  32370. vertexData.positions = positions;
  32371. vertexData.normals = normals;
  32372. vertexData.uvs = uvs;
  32373. return vertexData;
  32374. };
  32375. // Tools
  32376. /**
  32377. * @param {any} - positions (number[] or Float32Array)
  32378. * @param {any} - indices (number[] or Uint16Array)
  32379. * @param {any} - normals (number[] or Float32Array)
  32380. * options (optional) :
  32381. * facetPositions : optional array of facet positions (vector3)
  32382. * facetNormals : optional array of facet normals (vector3)
  32383. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  32384. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  32385. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  32386. * bbSize : optional bounding box size data, required for facetPartitioning computation
  32387. * bInfo : optional bounding info, required for facetPartitioning computation
  32388. * useRightHandedSystem: optional boolean to for right handed system computation
  32389. * depthSort : optional boolean to enable the facet depth sort computation
  32390. * distanceTo : optional Vector3 to compute the facet depth from this location
  32391. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  32392. */
  32393. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  32394. // temporary scalar variables
  32395. var index = 0; // facet index
  32396. var p1p2x = 0.0; // p1p2 vector x coordinate
  32397. var p1p2y = 0.0; // p1p2 vector y coordinate
  32398. var p1p2z = 0.0; // p1p2 vector z coordinate
  32399. var p3p2x = 0.0; // p3p2 vector x coordinate
  32400. var p3p2y = 0.0; // p3p2 vector y coordinate
  32401. var p3p2z = 0.0; // p3p2 vector z coordinate
  32402. var faceNormalx = 0.0; // facet normal x coordinate
  32403. var faceNormaly = 0.0; // facet normal y coordinate
  32404. var faceNormalz = 0.0; // facet normal z coordinate
  32405. var length = 0.0; // facet normal length before normalization
  32406. var v1x = 0; // vector1 x index in the positions array
  32407. var v1y = 0; // vector1 y index in the positions array
  32408. var v1z = 0; // vector1 z index in the positions array
  32409. var v2x = 0; // vector2 x index in the positions array
  32410. var v2y = 0; // vector2 y index in the positions array
  32411. var v2z = 0; // vector2 z index in the positions array
  32412. var v3x = 0; // vector3 x index in the positions array
  32413. var v3y = 0; // vector3 y index in the positions array
  32414. var v3z = 0; // vector3 z index in the positions array
  32415. var computeFacetNormals = false;
  32416. var computeFacetPositions = false;
  32417. var computeFacetPartitioning = false;
  32418. var computeDepthSort = false;
  32419. var faceNormalSign = 1;
  32420. var ratio = 0;
  32421. var distanceTo = null;
  32422. if (options) {
  32423. computeFacetNormals = (options.facetNormals) ? true : false;
  32424. computeFacetPositions = (options.facetPositions) ? true : false;
  32425. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  32426. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  32427. ratio = options.ratio || 0;
  32428. computeDepthSort = (options.depthSort) ? true : false;
  32429. distanceTo = (options.distanceTo);
  32430. if (computeDepthSort) {
  32431. if (distanceTo === undefined) {
  32432. distanceTo = BABYLON.Vector3.Zero();
  32433. }
  32434. var depthSortedFacets = options.depthSortedFacets;
  32435. }
  32436. }
  32437. // facetPartitioning reinit if needed
  32438. var xSubRatio = 0;
  32439. var ySubRatio = 0;
  32440. var zSubRatio = 0;
  32441. var subSq = 0;
  32442. if (computeFacetPartitioning && options && options.bbSize) {
  32443. var ox = 0; // X partitioning index for facet position
  32444. var oy = 0; // Y partinioning index for facet position
  32445. var oz = 0; // Z partinioning index for facet position
  32446. var b1x = 0; // X partitioning index for facet v1 vertex
  32447. var b1y = 0; // Y partitioning index for facet v1 vertex
  32448. var b1z = 0; // z partitioning index for facet v1 vertex
  32449. var b2x = 0; // X partitioning index for facet v2 vertex
  32450. var b2y = 0; // Y partitioning index for facet v2 vertex
  32451. var b2z = 0; // Z partitioning index for facet v2 vertex
  32452. var b3x = 0; // X partitioning index for facet v3 vertex
  32453. var b3y = 0; // Y partitioning index for facet v3 vertex
  32454. var b3z = 0; // Z partitioning index for facet v3 vertex
  32455. var block_idx_o = 0; // facet barycenter block index
  32456. var block_idx_v1 = 0; // v1 vertex block index
  32457. var block_idx_v2 = 0; // v2 vertex block index
  32458. var block_idx_v3 = 0; // v3 vertex block index
  32459. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  32460. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  32461. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  32462. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  32463. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  32464. subSq = options.subDiv.max * options.subDiv.max;
  32465. options.facetPartitioning.length = 0;
  32466. }
  32467. // reset the normals
  32468. for (index = 0; index < positions.length; index++) {
  32469. normals[index] = 0.0;
  32470. }
  32471. // Loop : 1 indice triplet = 1 facet
  32472. var nbFaces = (indices.length / 3) | 0;
  32473. for (index = 0; index < nbFaces; index++) {
  32474. // get the indexes of the coordinates of each vertex of the facet
  32475. v1x = indices[index * 3] * 3;
  32476. v1y = v1x + 1;
  32477. v1z = v1x + 2;
  32478. v2x = indices[index * 3 + 1] * 3;
  32479. v2y = v2x + 1;
  32480. v2z = v2x + 2;
  32481. v3x = indices[index * 3 + 2] * 3;
  32482. v3y = v3x + 1;
  32483. v3z = v3x + 2;
  32484. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  32485. p1p2y = positions[v1y] - positions[v2y];
  32486. p1p2z = positions[v1z] - positions[v2z];
  32487. p3p2x = positions[v3x] - positions[v2x];
  32488. p3p2y = positions[v3y] - positions[v2y];
  32489. p3p2z = positions[v3z] - positions[v2z];
  32490. // compute the face normal with the cross product
  32491. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  32492. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  32493. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  32494. // normalize this normal and store it in the array facetData
  32495. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32496. length = (length === 0) ? 1.0 : length;
  32497. faceNormalx /= length;
  32498. faceNormaly /= length;
  32499. faceNormalz /= length;
  32500. if (computeFacetNormals && options) {
  32501. options.facetNormals[index].x = faceNormalx;
  32502. options.facetNormals[index].y = faceNormaly;
  32503. options.facetNormals[index].z = faceNormalz;
  32504. }
  32505. if (computeFacetPositions && options) {
  32506. // compute and the facet barycenter coordinates in the array facetPositions
  32507. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  32508. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  32509. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  32510. }
  32511. if (computeFacetPartitioning && options) {
  32512. // store the facet indexes in arrays in the main facetPartitioning array :
  32513. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  32514. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  32515. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  32516. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  32517. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32518. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32519. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32520. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32521. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32522. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32523. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32524. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32525. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32526. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  32527. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  32528. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  32529. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  32530. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  32531. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  32532. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  32533. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  32534. // push each facet index in each block containing the vertex
  32535. options.facetPartitioning[block_idx_v1].push(index);
  32536. if (block_idx_v2 != block_idx_v1) {
  32537. options.facetPartitioning[block_idx_v2].push(index);
  32538. }
  32539. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  32540. options.facetPartitioning[block_idx_v3].push(index);
  32541. }
  32542. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  32543. options.facetPartitioning[block_idx_o].push(index);
  32544. }
  32545. }
  32546. if (computeDepthSort && options && options.facetPositions) {
  32547. var dsf = depthSortedFacets[index];
  32548. dsf.ind = index * 3;
  32549. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  32550. }
  32551. // compute the normals anyway
  32552. normals[v1x] += faceNormalx; // accumulate all the normals per face
  32553. normals[v1y] += faceNormaly;
  32554. normals[v1z] += faceNormalz;
  32555. normals[v2x] += faceNormalx;
  32556. normals[v2y] += faceNormaly;
  32557. normals[v2z] += faceNormalz;
  32558. normals[v3x] += faceNormalx;
  32559. normals[v3y] += faceNormaly;
  32560. normals[v3z] += faceNormalz;
  32561. }
  32562. // last normalization of each normal
  32563. for (index = 0; index < normals.length / 3; index++) {
  32564. faceNormalx = normals[index * 3];
  32565. faceNormaly = normals[index * 3 + 1];
  32566. faceNormalz = normals[index * 3 + 2];
  32567. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32568. length = (length === 0) ? 1.0 : length;
  32569. faceNormalx /= length;
  32570. faceNormaly /= length;
  32571. faceNormalz /= length;
  32572. normals[index * 3] = faceNormalx;
  32573. normals[index * 3 + 1] = faceNormaly;
  32574. normals[index * 3 + 2] = faceNormalz;
  32575. }
  32576. };
  32577. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  32578. var li = indices.length;
  32579. var ln = normals.length;
  32580. var i;
  32581. var n;
  32582. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32583. switch (sideOrientation) {
  32584. case BABYLON.Mesh.FRONTSIDE:
  32585. // nothing changed
  32586. break;
  32587. case BABYLON.Mesh.BACKSIDE:
  32588. var tmp;
  32589. // indices
  32590. for (i = 0; i < li; i += 3) {
  32591. tmp = indices[i];
  32592. indices[i] = indices[i + 2];
  32593. indices[i + 2] = tmp;
  32594. }
  32595. // normals
  32596. for (n = 0; n < ln; n++) {
  32597. normals[n] = -normals[n];
  32598. }
  32599. break;
  32600. case BABYLON.Mesh.DOUBLESIDE:
  32601. // positions
  32602. var lp = positions.length;
  32603. var l = lp / 3;
  32604. for (var p = 0; p < lp; p++) {
  32605. positions[lp + p] = positions[p];
  32606. }
  32607. // indices
  32608. for (i = 0; i < li; i += 3) {
  32609. indices[i + li] = indices[i + 2] + l;
  32610. indices[i + 1 + li] = indices[i + 1] + l;
  32611. indices[i + 2 + li] = indices[i] + l;
  32612. }
  32613. // normals
  32614. for (n = 0; n < ln; n++) {
  32615. normals[ln + n] = -normals[n];
  32616. }
  32617. // uvs
  32618. var lu = uvs.length;
  32619. var u = 0;
  32620. for (u = 0; u < lu; u++) {
  32621. uvs[u + lu] = uvs[u];
  32622. }
  32623. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32624. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32625. u = 0;
  32626. for (i = 0; i < lu / 2; i++) {
  32627. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  32628. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  32629. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  32630. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  32631. u += 2;
  32632. }
  32633. break;
  32634. }
  32635. };
  32636. /**
  32637. * Creates a new VertexData from the imported parameters.
  32638. */
  32639. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32640. var vertexData = new VertexData();
  32641. // positions
  32642. var positions = parsedVertexData.positions;
  32643. if (positions) {
  32644. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32645. }
  32646. // normals
  32647. var normals = parsedVertexData.normals;
  32648. if (normals) {
  32649. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32650. }
  32651. // tangents
  32652. var tangents = parsedVertexData.tangents;
  32653. if (tangents) {
  32654. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  32655. }
  32656. // uvs
  32657. var uvs = parsedVertexData.uvs;
  32658. if (uvs) {
  32659. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32660. }
  32661. // uv2s
  32662. var uv2s = parsedVertexData.uv2s;
  32663. if (uv2s) {
  32664. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32665. }
  32666. // uv3s
  32667. var uv3s = parsedVertexData.uv3s;
  32668. if (uv3s) {
  32669. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32670. }
  32671. // uv4s
  32672. var uv4s = parsedVertexData.uv4s;
  32673. if (uv4s) {
  32674. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32675. }
  32676. // uv5s
  32677. var uv5s = parsedVertexData.uv5s;
  32678. if (uv5s) {
  32679. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32680. }
  32681. // uv6s
  32682. var uv6s = parsedVertexData.uv6s;
  32683. if (uv6s) {
  32684. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32685. }
  32686. // colors
  32687. var colors = parsedVertexData.colors;
  32688. if (colors) {
  32689. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32690. }
  32691. // matricesIndices
  32692. var matricesIndices = parsedVertexData.matricesIndices;
  32693. if (matricesIndices) {
  32694. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32695. }
  32696. // matricesWeights
  32697. var matricesWeights = parsedVertexData.matricesWeights;
  32698. if (matricesWeights) {
  32699. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32700. }
  32701. // indices
  32702. var indices = parsedVertexData.indices;
  32703. if (indices) {
  32704. vertexData.indices = indices;
  32705. }
  32706. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32707. };
  32708. return VertexData;
  32709. }());
  32710. BABYLON.VertexData = VertexData;
  32711. })(BABYLON || (BABYLON = {}));
  32712. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  32713. var BABYLON;
  32714. (function (BABYLON) {
  32715. /**
  32716. * Class used to store geometry data (vertex buffers + index buffer)
  32717. */
  32718. var Geometry = /** @class */ (function () {
  32719. /**
  32720. * Creates a new geometry
  32721. * @param id defines the unique ID
  32722. * @param scene defines the hosting scene
  32723. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  32724. * @param updatable defines if geometry must be updatable (false by default)
  32725. * @param mesh defines the mesh that will be associated with the geometry
  32726. */
  32727. function Geometry(id, scene, vertexData, updatable, mesh) {
  32728. if (updatable === void 0) { updatable = false; }
  32729. if (mesh === void 0) { mesh = null; }
  32730. /**
  32731. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32732. */
  32733. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32734. this._totalVertices = 0;
  32735. this._isDisposed = false;
  32736. this._indexBufferIsUpdatable = false;
  32737. this.id = id;
  32738. this._engine = scene.getEngine();
  32739. this._meshes = [];
  32740. this._scene = scene;
  32741. //Init vertex buffer cache
  32742. this._vertexBuffers = {};
  32743. this._indices = [];
  32744. this._updatable = updatable;
  32745. // vertexData
  32746. if (vertexData) {
  32747. this.setAllVerticesData(vertexData, updatable);
  32748. }
  32749. else {
  32750. this._totalVertices = 0;
  32751. this._indices = [];
  32752. }
  32753. if (this._engine.getCaps().vertexArrayObject) {
  32754. this._vertexArrayObjects = {};
  32755. }
  32756. // applyToMesh
  32757. if (mesh) {
  32758. if (mesh.getClassName() === "LinesMesh") {
  32759. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32760. this.updateExtend();
  32761. }
  32762. this.applyToMesh(mesh);
  32763. mesh.computeWorldMatrix(true);
  32764. }
  32765. }
  32766. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32767. /**
  32768. * 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
  32769. */
  32770. get: function () {
  32771. return this._boundingBias;
  32772. },
  32773. /**
  32774. * 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
  32775. */
  32776. set: function (value) {
  32777. if (this._boundingBias && this._boundingBias.equals(value)) {
  32778. return;
  32779. }
  32780. this._boundingBias = value.clone();
  32781. this.updateBoundingInfo(true, null);
  32782. },
  32783. enumerable: true,
  32784. configurable: true
  32785. });
  32786. /**
  32787. * Static function used to attach a new empty geometry to a mesh
  32788. * @param mesh defines the mesh to attach the geometry to
  32789. * @returns the new {BABYLON.Geometry}
  32790. */
  32791. Geometry.CreateGeometryForMesh = function (mesh) {
  32792. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32793. geometry.applyToMesh(mesh);
  32794. return geometry;
  32795. };
  32796. Object.defineProperty(Geometry.prototype, "extend", {
  32797. /**
  32798. * Gets the current extend of the geometry
  32799. */
  32800. get: function () {
  32801. return this._extend;
  32802. },
  32803. enumerable: true,
  32804. configurable: true
  32805. });
  32806. /**
  32807. * Gets the hosting scene
  32808. * @returns the hosting {BABYLON.Scene}
  32809. */
  32810. Geometry.prototype.getScene = function () {
  32811. return this._scene;
  32812. };
  32813. /**
  32814. * Gets the hosting engine
  32815. * @returns the hosting {BABYLON.Engine}
  32816. */
  32817. Geometry.prototype.getEngine = function () {
  32818. return this._engine;
  32819. };
  32820. /**
  32821. * Defines if the geometry is ready to use
  32822. * @returns true if the geometry is ready to be used
  32823. */
  32824. Geometry.prototype.isReady = function () {
  32825. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32826. };
  32827. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32828. /**
  32829. * Gets a value indicating that the geometry should not be serialized
  32830. */
  32831. get: function () {
  32832. for (var index = 0; index < this._meshes.length; index++) {
  32833. if (!this._meshes[index].doNotSerialize) {
  32834. return false;
  32835. }
  32836. }
  32837. return true;
  32838. },
  32839. enumerable: true,
  32840. configurable: true
  32841. });
  32842. /** @ignore */
  32843. Geometry.prototype._rebuild = function () {
  32844. if (this._vertexArrayObjects) {
  32845. this._vertexArrayObjects = {};
  32846. }
  32847. // Index buffer
  32848. if (this._meshes.length !== 0 && this._indices) {
  32849. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32850. }
  32851. // Vertex buffers
  32852. for (var key in this._vertexBuffers) {
  32853. var vertexBuffer = this._vertexBuffers[key];
  32854. vertexBuffer._rebuild();
  32855. }
  32856. };
  32857. /**
  32858. * Affects all gemetry data in one call
  32859. * @param vertexData defines the geometry data
  32860. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32861. */
  32862. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32863. vertexData.applyToGeometry(this, updatable);
  32864. this.notifyUpdate();
  32865. };
  32866. /**
  32867. * Set specific vertex data
  32868. * @param kind defines the data kind (Position, normal, etc...)
  32869. * @param data defines the vertex data to use
  32870. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32871. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32872. */
  32873. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32874. if (updatable === void 0) { updatable = false; }
  32875. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32876. this.setVerticesBuffer(buffer);
  32877. };
  32878. /**
  32879. * Removes a specific vertex data
  32880. * @param kind defines the data kind (Position, normal, etc...)
  32881. */
  32882. Geometry.prototype.removeVerticesData = function (kind) {
  32883. if (this._vertexBuffers[kind]) {
  32884. this._vertexBuffers[kind].dispose();
  32885. delete this._vertexBuffers[kind];
  32886. }
  32887. };
  32888. /**
  32889. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32890. * @param buffer defines the vertex buffer to use
  32891. */
  32892. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32893. var kind = buffer.getKind();
  32894. if (this._vertexBuffers[kind]) {
  32895. this._vertexBuffers[kind].dispose();
  32896. }
  32897. this._vertexBuffers[kind] = buffer;
  32898. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32899. var data = buffer.getData();
  32900. var stride = buffer.getStrideSize();
  32901. this._totalVertices = data.length / stride;
  32902. this.updateExtend(data, stride);
  32903. this._resetPointsArrayCache();
  32904. var meshes = this._meshes;
  32905. var numOfMeshes = meshes.length;
  32906. for (var index = 0; index < numOfMeshes; index++) {
  32907. var mesh = meshes[index];
  32908. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32909. mesh._createGlobalSubMesh(false);
  32910. mesh.computeWorldMatrix(true);
  32911. }
  32912. }
  32913. this.notifyUpdate(kind);
  32914. if (this._vertexArrayObjects) {
  32915. this._disposeVertexArrayObjects();
  32916. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32917. }
  32918. };
  32919. /**
  32920. * Update a specific vertex buffer
  32921. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32922. * It will do nothing if the buffer is not updatable
  32923. * @param kind defines the data kind (Position, normal, etc...)
  32924. * @param data defines the data to use
  32925. * @param offset defines the offset in the target buffer where to store the data
  32926. */
  32927. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32928. var vertexBuffer = this.getVertexBuffer(kind);
  32929. if (!vertexBuffer) {
  32930. return;
  32931. }
  32932. vertexBuffer.updateDirectly(data, offset);
  32933. this.notifyUpdate(kind);
  32934. };
  32935. /**
  32936. * Update a specific vertex buffer
  32937. * This function will create a new buffer if the current one is not updatable
  32938. * @param kind defines the data kind (Position, normal, etc...)
  32939. * @param data defines the data to use
  32940. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32941. */
  32942. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32943. if (updateExtends === void 0) { updateExtends = false; }
  32944. var vertexBuffer = this.getVertexBuffer(kind);
  32945. if (!vertexBuffer) {
  32946. return;
  32947. }
  32948. vertexBuffer.update(data);
  32949. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32950. var stride = vertexBuffer.getStrideSize();
  32951. this._totalVertices = data.length / stride;
  32952. this.updateBoundingInfo(updateExtends, data);
  32953. }
  32954. this.notifyUpdate(kind);
  32955. };
  32956. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32957. if (updateExtends) {
  32958. this.updateExtend(data);
  32959. }
  32960. var meshes = this._meshes;
  32961. var numOfMeshes = meshes.length;
  32962. this._resetPointsArrayCache();
  32963. for (var index = 0; index < numOfMeshes; index++) {
  32964. var mesh = meshes[index];
  32965. if (updateExtends) {
  32966. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32967. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32968. var subMesh = mesh.subMeshes[subIndex];
  32969. subMesh.refreshBoundingInfo();
  32970. }
  32971. }
  32972. }
  32973. };
  32974. /** @ignore */
  32975. Geometry.prototype._bind = function (effect, indexToBind) {
  32976. if (!effect) {
  32977. return;
  32978. }
  32979. if (indexToBind === undefined) {
  32980. indexToBind = this._indexBuffer;
  32981. }
  32982. var vbs = this.getVertexBuffers();
  32983. if (!vbs) {
  32984. return;
  32985. }
  32986. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32987. this._engine.bindBuffers(vbs, indexToBind, effect);
  32988. return;
  32989. }
  32990. // Using VAO
  32991. if (!this._vertexArrayObjects[effect.key]) {
  32992. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32993. }
  32994. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32995. };
  32996. /**
  32997. * Gets total number of vertices
  32998. * @returns the total number of vertices
  32999. */
  33000. Geometry.prototype.getTotalVertices = function () {
  33001. if (!this.isReady()) {
  33002. return 0;
  33003. }
  33004. return this._totalVertices;
  33005. };
  33006. /**
  33007. * Gets a specific vertex data attached to this geometry
  33008. * @param kind defines the data kind (Position, normal, etc...)
  33009. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  33010. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  33011. * @returns a float array containing vertex data
  33012. */
  33013. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  33014. var vertexBuffer = this.getVertexBuffer(kind);
  33015. if (!vertexBuffer) {
  33016. return null;
  33017. }
  33018. var orig = vertexBuffer.getData();
  33019. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  33020. return orig;
  33021. }
  33022. else {
  33023. var len = orig.length;
  33024. var copy = [];
  33025. for (var i = 0; i < len; i++) {
  33026. copy.push(orig[i]);
  33027. }
  33028. return copy;
  33029. }
  33030. };
  33031. /**
  33032. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  33033. * @param kind defines the data kind (Position, normal, etc...)
  33034. * @returns true if the vertex buffer with the specified kind is updatable
  33035. */
  33036. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  33037. var vb = this._vertexBuffers[kind];
  33038. if (!vb) {
  33039. return false;
  33040. }
  33041. return vb.isUpdatable();
  33042. };
  33043. /**
  33044. * Gets a specific vertex buffer
  33045. * @param kind defines the data kind (Position, normal, etc...)
  33046. * @returns a {BABYLON.VertexBuffer}
  33047. */
  33048. Geometry.prototype.getVertexBuffer = function (kind) {
  33049. if (!this.isReady()) {
  33050. return null;
  33051. }
  33052. return this._vertexBuffers[kind];
  33053. };
  33054. /**
  33055. * Returns all vertex buffers
  33056. * @return an object holding all vertex buffers indexed by kind
  33057. */
  33058. Geometry.prototype.getVertexBuffers = function () {
  33059. if (!this.isReady()) {
  33060. return null;
  33061. }
  33062. return this._vertexBuffers;
  33063. };
  33064. /**
  33065. * Gets a boolean indicating if specific vertex buffer is present
  33066. * @param kind defines the data kind (Position, normal, etc...)
  33067. * @returns true if data is present
  33068. */
  33069. Geometry.prototype.isVerticesDataPresent = function (kind) {
  33070. if (!this._vertexBuffers) {
  33071. if (this._delayInfo) {
  33072. return this._delayInfo.indexOf(kind) !== -1;
  33073. }
  33074. return false;
  33075. }
  33076. return this._vertexBuffers[kind] !== undefined;
  33077. };
  33078. /**
  33079. * Gets a list of all attached data kinds (Position, normal, etc...)
  33080. * @returns a list of string containing all kinds
  33081. */
  33082. Geometry.prototype.getVerticesDataKinds = function () {
  33083. var result = [];
  33084. var kind;
  33085. if (!this._vertexBuffers && this._delayInfo) {
  33086. for (kind in this._delayInfo) {
  33087. result.push(kind);
  33088. }
  33089. }
  33090. else {
  33091. for (kind in this._vertexBuffers) {
  33092. result.push(kind);
  33093. }
  33094. }
  33095. return result;
  33096. };
  33097. /**
  33098. * Update index buffer
  33099. * @param indices defines the indices to store in the index buffer
  33100. * @param offset defines the offset in the target buffer where to store the data
  33101. */
  33102. Geometry.prototype.updateIndices = function (indices, offset) {
  33103. if (!this._indexBuffer) {
  33104. return;
  33105. }
  33106. if (!this._indexBufferIsUpdatable) {
  33107. this.setIndices(indices, null, true);
  33108. }
  33109. else {
  33110. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  33111. }
  33112. };
  33113. /**
  33114. * Creates a new index buffer
  33115. * @param indices defines the indices to store in the index buffer
  33116. * @param totalVertices defines the total number of vertices (could be null)
  33117. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  33118. */
  33119. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  33120. if (totalVertices === void 0) { totalVertices = null; }
  33121. if (updatable === void 0) { updatable = false; }
  33122. if (this._indexBuffer) {
  33123. this._engine._releaseBuffer(this._indexBuffer);
  33124. }
  33125. this._disposeVertexArrayObjects();
  33126. this._indices = indices;
  33127. this._indexBufferIsUpdatable = updatable;
  33128. if (this._meshes.length !== 0 && this._indices) {
  33129. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  33130. }
  33131. if (totalVertices != undefined) {
  33132. this._totalVertices = totalVertices;
  33133. }
  33134. var meshes = this._meshes;
  33135. var numOfMeshes = meshes.length;
  33136. for (var index = 0; index < numOfMeshes; index++) {
  33137. meshes[index]._createGlobalSubMesh(true);
  33138. }
  33139. this.notifyUpdate();
  33140. };
  33141. /**
  33142. * Return the total number of indices
  33143. * @returns the total number of indices
  33144. */
  33145. Geometry.prototype.getTotalIndices = function () {
  33146. if (!this.isReady()) {
  33147. return 0;
  33148. }
  33149. return this._indices.length;
  33150. };
  33151. /**
  33152. * Gets the index buffer array
  33153. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  33154. * @returns the index buffer array
  33155. */
  33156. Geometry.prototype.getIndices = function (copyWhenShared) {
  33157. if (!this.isReady()) {
  33158. return null;
  33159. }
  33160. var orig = this._indices;
  33161. if (!copyWhenShared || this._meshes.length === 1) {
  33162. return orig;
  33163. }
  33164. else {
  33165. var len = orig.length;
  33166. var copy = [];
  33167. for (var i = 0; i < len; i++) {
  33168. copy.push(orig[i]);
  33169. }
  33170. return copy;
  33171. }
  33172. };
  33173. /**
  33174. * Gets the index buffer
  33175. * @return the index buffer
  33176. */
  33177. Geometry.prototype.getIndexBuffer = function () {
  33178. if (!this.isReady()) {
  33179. return null;
  33180. }
  33181. return this._indexBuffer;
  33182. };
  33183. /** @ignore */
  33184. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  33185. if (effect === void 0) { effect = null; }
  33186. if (!effect || !this._vertexArrayObjects) {
  33187. return;
  33188. }
  33189. if (this._vertexArrayObjects[effect.key]) {
  33190. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  33191. delete this._vertexArrayObjects[effect.key];
  33192. }
  33193. };
  33194. /**
  33195. * Release the associated resources for a specific mesh
  33196. * @param mesh defines the source mesh
  33197. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  33198. */
  33199. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33200. var meshes = this._meshes;
  33201. var index = meshes.indexOf(mesh);
  33202. if (index === -1) {
  33203. return;
  33204. }
  33205. meshes.splice(index, 1);
  33206. mesh._geometry = null;
  33207. if (meshes.length === 0 && shouldDispose) {
  33208. this.dispose();
  33209. }
  33210. };
  33211. /**
  33212. * Apply current geometry to a given mesh
  33213. * @param mesh defines the mesh to apply geometry to
  33214. */
  33215. Geometry.prototype.applyToMesh = function (mesh) {
  33216. if (mesh._geometry === this) {
  33217. return;
  33218. }
  33219. var previousGeometry = mesh._geometry;
  33220. if (previousGeometry) {
  33221. previousGeometry.releaseForMesh(mesh);
  33222. }
  33223. var meshes = this._meshes;
  33224. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33225. mesh._geometry = this;
  33226. this._scene.pushGeometry(this);
  33227. meshes.push(mesh);
  33228. if (this.isReady()) {
  33229. this._applyToMesh(mesh);
  33230. }
  33231. else {
  33232. mesh._boundingInfo = this._boundingInfo;
  33233. }
  33234. };
  33235. Geometry.prototype.updateExtend = function (data, stride) {
  33236. if (data === void 0) { data = null; }
  33237. if (!data) {
  33238. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33239. }
  33240. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33241. };
  33242. Geometry.prototype._applyToMesh = function (mesh) {
  33243. var numOfMeshes = this._meshes.length;
  33244. // vertexBuffers
  33245. for (var kind in this._vertexBuffers) {
  33246. if (numOfMeshes === 1) {
  33247. this._vertexBuffers[kind].create();
  33248. }
  33249. var buffer = this._vertexBuffers[kind].getBuffer();
  33250. if (buffer)
  33251. buffer.references = numOfMeshes;
  33252. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33253. if (!this._extend) {
  33254. this.updateExtend(this._vertexBuffers[kind].getData());
  33255. }
  33256. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33257. mesh._createGlobalSubMesh(false);
  33258. //bounding info was just created again, world matrix should be applied again.
  33259. mesh._updateBoundingInfo();
  33260. }
  33261. }
  33262. // indexBuffer
  33263. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33264. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33265. }
  33266. if (this._indexBuffer) {
  33267. this._indexBuffer.references = numOfMeshes;
  33268. }
  33269. };
  33270. Geometry.prototype.notifyUpdate = function (kind) {
  33271. if (this.onGeometryUpdated) {
  33272. this.onGeometryUpdated(this, kind);
  33273. }
  33274. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  33275. var mesh = _a[_i];
  33276. mesh._markSubMeshesAsAttributesDirty();
  33277. }
  33278. };
  33279. /**
  33280. * Load the geometry if it was flagged as delay loaded
  33281. * @param scene defines the hosting scene
  33282. * @param onLoaded defines a callback called when the geometry is loaded
  33283. */
  33284. Geometry.prototype.load = function (scene, onLoaded) {
  33285. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33286. return;
  33287. }
  33288. if (this.isReady()) {
  33289. if (onLoaded) {
  33290. onLoaded();
  33291. }
  33292. return;
  33293. }
  33294. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33295. this._queueLoad(scene, onLoaded);
  33296. };
  33297. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33298. var _this = this;
  33299. if (!this.delayLoadingFile) {
  33300. return;
  33301. }
  33302. scene._addPendingData(this);
  33303. scene._loadFile(this.delayLoadingFile, function (data) {
  33304. if (!_this._delayLoadingFunction) {
  33305. return;
  33306. }
  33307. _this._delayLoadingFunction(JSON.parse(data), _this);
  33308. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33309. _this._delayInfo = [];
  33310. scene._removePendingData(_this);
  33311. var meshes = _this._meshes;
  33312. var numOfMeshes = meshes.length;
  33313. for (var index = 0; index < numOfMeshes; index++) {
  33314. _this._applyToMesh(meshes[index]);
  33315. }
  33316. if (onLoaded) {
  33317. onLoaded();
  33318. }
  33319. }, undefined, true);
  33320. };
  33321. /**
  33322. * Invert the geometry to move from a right handed system to a left handed one.
  33323. */
  33324. Geometry.prototype.toLeftHanded = function () {
  33325. // Flip faces
  33326. var tIndices = this.getIndices(false);
  33327. if (tIndices != null && tIndices.length > 0) {
  33328. for (var i = 0; i < tIndices.length; i += 3) {
  33329. var tTemp = tIndices[i + 0];
  33330. tIndices[i + 0] = tIndices[i + 2];
  33331. tIndices[i + 2] = tTemp;
  33332. }
  33333. this.setIndices(tIndices);
  33334. }
  33335. // Negate position.z
  33336. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33337. if (tPositions != null && tPositions.length > 0) {
  33338. for (var i = 0; i < tPositions.length; i += 3) {
  33339. tPositions[i + 2] = -tPositions[i + 2];
  33340. }
  33341. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33342. }
  33343. // Negate normal.z
  33344. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33345. if (tNormals != null && tNormals.length > 0) {
  33346. for (var i = 0; i < tNormals.length; i += 3) {
  33347. tNormals[i + 2] = -tNormals[i + 2];
  33348. }
  33349. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33350. }
  33351. };
  33352. // Cache
  33353. /** @ignore */
  33354. Geometry.prototype._resetPointsArrayCache = function () {
  33355. this._positions = null;
  33356. };
  33357. /** @ignore */
  33358. Geometry.prototype._generatePointsArray = function () {
  33359. if (this._positions)
  33360. return true;
  33361. this._positions = [];
  33362. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33363. if (!data) {
  33364. return false;
  33365. }
  33366. for (var index = 0; index < data.length; index += 3) {
  33367. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  33368. }
  33369. return true;
  33370. };
  33371. /**
  33372. * Gets a value indicating if the geometry is disposed
  33373. * @returns true if the geometry was disposed
  33374. */
  33375. Geometry.prototype.isDisposed = function () {
  33376. return this._isDisposed;
  33377. };
  33378. Geometry.prototype._disposeVertexArrayObjects = function () {
  33379. if (this._vertexArrayObjects) {
  33380. for (var kind in this._vertexArrayObjects) {
  33381. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  33382. }
  33383. this._vertexArrayObjects = {};
  33384. }
  33385. };
  33386. /**
  33387. * Free all associated resources
  33388. */
  33389. Geometry.prototype.dispose = function () {
  33390. var meshes = this._meshes;
  33391. var numOfMeshes = meshes.length;
  33392. var index;
  33393. for (index = 0; index < numOfMeshes; index++) {
  33394. this.releaseForMesh(meshes[index]);
  33395. }
  33396. this._meshes = [];
  33397. this._disposeVertexArrayObjects();
  33398. for (var kind in this._vertexBuffers) {
  33399. this._vertexBuffers[kind].dispose();
  33400. }
  33401. this._vertexBuffers = {};
  33402. this._totalVertices = 0;
  33403. if (this._indexBuffer) {
  33404. this._engine._releaseBuffer(this._indexBuffer);
  33405. }
  33406. this._indexBuffer = null;
  33407. this._indices = [];
  33408. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33409. this.delayLoadingFile = null;
  33410. this._delayLoadingFunction = null;
  33411. this._delayInfo = [];
  33412. this._boundingInfo = null;
  33413. this._scene.removeGeometry(this);
  33414. this._isDisposed = true;
  33415. };
  33416. /**
  33417. * Clone the current geometry into a new geometry
  33418. * @param id defines the unique ID of the new geometry
  33419. * @returns a new geometry object
  33420. */
  33421. Geometry.prototype.copy = function (id) {
  33422. var vertexData = new BABYLON.VertexData();
  33423. vertexData.indices = [];
  33424. var indices = this.getIndices();
  33425. if (indices) {
  33426. for (var index = 0; index < indices.length; index++) {
  33427. vertexData.indices.push(indices[index]);
  33428. }
  33429. }
  33430. var updatable = false;
  33431. var stopChecking = false;
  33432. var kind;
  33433. for (kind in this._vertexBuffers) {
  33434. // using slice() to make a copy of the array and not just reference it
  33435. var data = this.getVerticesData(kind);
  33436. if (data instanceof Float32Array) {
  33437. vertexData.set(new Float32Array(data), kind);
  33438. }
  33439. else {
  33440. vertexData.set(data.slice(0), kind);
  33441. }
  33442. if (!stopChecking) {
  33443. var vb = this.getVertexBuffer(kind);
  33444. if (vb) {
  33445. updatable = vb.isUpdatable();
  33446. stopChecking = !updatable;
  33447. }
  33448. }
  33449. }
  33450. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  33451. geometry.delayLoadState = this.delayLoadState;
  33452. geometry.delayLoadingFile = this.delayLoadingFile;
  33453. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33454. for (kind in this._delayInfo) {
  33455. geometry._delayInfo = geometry._delayInfo || [];
  33456. geometry._delayInfo.push(kind);
  33457. }
  33458. // Bounding info
  33459. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33460. return geometry;
  33461. };
  33462. /**
  33463. * Serialize the current geometry info (and not the vertices data) into a JSON object
  33464. * @return a JSON representation of the current geometry data (without the vertices data)
  33465. */
  33466. Geometry.prototype.serialize = function () {
  33467. var serializationObject = {};
  33468. serializationObject.id = this.id;
  33469. serializationObject.updatable = this._updatable;
  33470. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33471. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33472. }
  33473. return serializationObject;
  33474. };
  33475. Geometry.prototype.toNumberArray = function (origin) {
  33476. if (Array.isArray(origin)) {
  33477. return origin;
  33478. }
  33479. else {
  33480. return Array.prototype.slice.call(origin);
  33481. }
  33482. };
  33483. /**
  33484. * Serialize all vertices data into a JSON oject
  33485. * @returns a JSON representation of the current geometry data
  33486. */
  33487. Geometry.prototype.serializeVerticeData = function () {
  33488. var serializationObject = this.serialize();
  33489. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33490. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  33491. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33492. serializationObject.positions._updatable = true;
  33493. }
  33494. }
  33495. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33496. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  33497. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33498. serializationObject.normals._updatable = true;
  33499. }
  33500. }
  33501. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33502. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  33503. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  33504. serializationObject.tangets._updatable = true;
  33505. }
  33506. }
  33507. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33508. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  33509. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  33510. serializationObject.uvs._updatable = true;
  33511. }
  33512. }
  33513. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33514. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  33515. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  33516. serializationObject.uv2s._updatable = true;
  33517. }
  33518. }
  33519. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33520. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  33521. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  33522. serializationObject.uv3s._updatable = true;
  33523. }
  33524. }
  33525. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33526. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  33527. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  33528. serializationObject.uv4s._updatable = true;
  33529. }
  33530. }
  33531. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33532. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  33533. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  33534. serializationObject.uv5s._updatable = true;
  33535. }
  33536. }
  33537. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33538. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  33539. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  33540. serializationObject.uv6s._updatable = true;
  33541. }
  33542. }
  33543. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33544. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  33545. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  33546. serializationObject.colors._updatable = true;
  33547. }
  33548. }
  33549. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33550. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  33551. serializationObject.matricesIndices._isExpanded = true;
  33552. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33553. serializationObject.matricesIndices._updatable = true;
  33554. }
  33555. }
  33556. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33557. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  33558. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33559. serializationObject.matricesWeights._updatable = true;
  33560. }
  33561. }
  33562. serializationObject.indices = this.toNumberArray(this.getIndices());
  33563. return serializationObject;
  33564. };
  33565. // Statics
  33566. /**
  33567. * Extracts a clone of a mesh geometry
  33568. * @param mesh defines the source mesh
  33569. * @param id defines the unique ID of the new geometry object
  33570. * @returns the new geometry object
  33571. */
  33572. Geometry.ExtractFromMesh = function (mesh, id) {
  33573. var geometry = mesh._geometry;
  33574. if (!geometry) {
  33575. return null;
  33576. }
  33577. return geometry.copy(id);
  33578. };
  33579. /**
  33580. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  33581. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33582. * Be aware Math.random() could cause collisions, but:
  33583. * "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"
  33584. * @returns a string containing a new GUID
  33585. */
  33586. Geometry.RandomId = function () {
  33587. return BABYLON.Tools.RandomId();
  33588. };
  33589. /** @ignore */
  33590. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  33591. var scene = mesh.getScene();
  33592. // Geometry
  33593. var geometryId = parsedGeometry.geometryId;
  33594. if (geometryId) {
  33595. var geometry = scene.getGeometryByID(geometryId);
  33596. if (geometry) {
  33597. geometry.applyToMesh(mesh);
  33598. }
  33599. }
  33600. else if (parsedGeometry instanceof ArrayBuffer) {
  33601. var binaryInfo = mesh._binaryInfo;
  33602. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33603. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33604. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33605. }
  33606. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33607. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33608. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33609. }
  33610. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  33611. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  33612. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  33613. }
  33614. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33615. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33616. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33617. }
  33618. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33619. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33620. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33621. }
  33622. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33623. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33624. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33625. }
  33626. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33627. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33628. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33629. }
  33630. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33631. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33632. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33633. }
  33634. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33635. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33636. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33637. }
  33638. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33639. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33640. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33641. }
  33642. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33643. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33644. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33645. }
  33646. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33647. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33648. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33649. }
  33650. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33651. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33652. mesh.setIndices(indicesData, null);
  33653. }
  33654. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33655. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33656. mesh.subMeshes = [];
  33657. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33658. var materialIndex = subMeshesData[(i * 5) + 0];
  33659. var verticesStart = subMeshesData[(i * 5) + 1];
  33660. var verticesCount = subMeshesData[(i * 5) + 2];
  33661. var indexStart = subMeshesData[(i * 5) + 3];
  33662. var indexCount = subMeshesData[(i * 5) + 4];
  33663. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33664. }
  33665. }
  33666. }
  33667. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33668. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  33669. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  33670. if (parsedGeometry.tangents) {
  33671. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  33672. }
  33673. if (parsedGeometry.uvs) {
  33674. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  33675. }
  33676. if (parsedGeometry.uvs2) {
  33677. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  33678. }
  33679. if (parsedGeometry.uvs3) {
  33680. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  33681. }
  33682. if (parsedGeometry.uvs4) {
  33683. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  33684. }
  33685. if (parsedGeometry.uvs5) {
  33686. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  33687. }
  33688. if (parsedGeometry.uvs6) {
  33689. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  33690. }
  33691. if (parsedGeometry.colors) {
  33692. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  33693. }
  33694. if (parsedGeometry.matricesIndices) {
  33695. if (!parsedGeometry.matricesIndices._isExpanded) {
  33696. var floatIndices = [];
  33697. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33698. var matricesIndex = parsedGeometry.matricesIndices[i];
  33699. floatIndices.push(matricesIndex & 0x000000FF);
  33700. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33701. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33702. floatIndices.push(matricesIndex >> 24);
  33703. }
  33704. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  33705. }
  33706. else {
  33707. delete parsedGeometry.matricesIndices._isExpanded;
  33708. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  33709. }
  33710. }
  33711. if (parsedGeometry.matricesIndicesExtra) {
  33712. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33713. var floatIndices = [];
  33714. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33715. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33716. floatIndices.push(matricesIndex & 0x000000FF);
  33717. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33718. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33719. floatIndices.push(matricesIndex >> 24);
  33720. }
  33721. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  33722. }
  33723. else {
  33724. delete parsedGeometry.matricesIndices._isExpanded;
  33725. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  33726. }
  33727. }
  33728. if (parsedGeometry.matricesWeights) {
  33729. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  33730. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  33731. }
  33732. if (parsedGeometry.matricesWeightsExtra) {
  33733. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  33734. }
  33735. mesh.setIndices(parsedGeometry.indices, null);
  33736. }
  33737. // SubMeshes
  33738. if (parsedGeometry.subMeshes) {
  33739. mesh.subMeshes = [];
  33740. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33741. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33742. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33743. }
  33744. }
  33745. // Flat shading
  33746. if (mesh._shouldGenerateFlatShading) {
  33747. mesh.convertToFlatShadedMesh();
  33748. delete mesh._shouldGenerateFlatShading;
  33749. }
  33750. // Update
  33751. mesh.computeWorldMatrix(true);
  33752. // Octree
  33753. var sceneOctree = scene.selectionOctree;
  33754. if (sceneOctree !== undefined && sceneOctree !== null) {
  33755. sceneOctree.addMesh(mesh);
  33756. }
  33757. };
  33758. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  33759. var epsilon = 1e-3;
  33760. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  33761. return;
  33762. }
  33763. var noInfluenceBoneIndex = 0.0;
  33764. if (parsedGeometry.skeletonId > -1) {
  33765. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  33766. if (!skeleton) {
  33767. return;
  33768. }
  33769. noInfluenceBoneIndex = skeleton.bones.length;
  33770. }
  33771. else {
  33772. return;
  33773. }
  33774. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33775. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33776. var matricesWeights = parsedGeometry.matricesWeights;
  33777. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  33778. var influencers = parsedGeometry.numBoneInfluencer;
  33779. var size = matricesWeights.length;
  33780. for (var i = 0; i < size; i += 4) {
  33781. var weight = 0.0;
  33782. var firstZeroWeight = -1;
  33783. for (var j = 0; j < 4; j++) {
  33784. var w = matricesWeights[i + j];
  33785. weight += w;
  33786. if (w < epsilon && firstZeroWeight < 0) {
  33787. firstZeroWeight = j;
  33788. }
  33789. }
  33790. if (matricesWeightsExtra) {
  33791. for (var j = 0; j < 4; j++) {
  33792. var w = matricesWeightsExtra[i + j];
  33793. weight += w;
  33794. if (w < epsilon && firstZeroWeight < 0) {
  33795. firstZeroWeight = j + 4;
  33796. }
  33797. }
  33798. }
  33799. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33800. firstZeroWeight = influencers - 1;
  33801. }
  33802. if (weight > epsilon) {
  33803. var mweight = 1.0 / weight;
  33804. for (var j = 0; j < 4; j++) {
  33805. matricesWeights[i + j] *= mweight;
  33806. }
  33807. if (matricesWeightsExtra) {
  33808. for (var j = 0; j < 4; j++) {
  33809. matricesWeightsExtra[i + j] *= mweight;
  33810. }
  33811. }
  33812. }
  33813. else {
  33814. if (firstZeroWeight >= 4) {
  33815. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33816. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33817. }
  33818. else {
  33819. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33820. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33821. }
  33822. }
  33823. }
  33824. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33825. if (parsedGeometry.matricesWeightsExtra) {
  33826. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33827. }
  33828. };
  33829. /**
  33830. * Create a new geometry from persisted data (Using .babylon file format)
  33831. * @param parsedVertexData defines the persisted data
  33832. * @param scene defines the hosting scene
  33833. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33834. * @returns the new geometry object
  33835. */
  33836. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33837. if (scene.getGeometryByID(parsedVertexData.id)) {
  33838. return null; // null since geometry could be something else than a box...
  33839. }
  33840. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33841. if (BABYLON.Tags) {
  33842. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33843. }
  33844. if (parsedVertexData.delayLoadingFile) {
  33845. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33846. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33847. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33848. geometry._delayInfo = [];
  33849. if (parsedVertexData.hasUVs) {
  33850. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33851. }
  33852. if (parsedVertexData.hasUVs2) {
  33853. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33854. }
  33855. if (parsedVertexData.hasUVs3) {
  33856. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33857. }
  33858. if (parsedVertexData.hasUVs4) {
  33859. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33860. }
  33861. if (parsedVertexData.hasUVs5) {
  33862. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33863. }
  33864. if (parsedVertexData.hasUVs6) {
  33865. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33866. }
  33867. if (parsedVertexData.hasColors) {
  33868. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33869. }
  33870. if (parsedVertexData.hasMatricesIndices) {
  33871. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33872. }
  33873. if (parsedVertexData.hasMatricesWeights) {
  33874. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33875. }
  33876. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33877. }
  33878. else {
  33879. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33880. }
  33881. scene.pushGeometry(geometry, true);
  33882. return geometry;
  33883. };
  33884. return Geometry;
  33885. }());
  33886. BABYLON.Geometry = Geometry;
  33887. // Primitives
  33888. /// Abstract class
  33889. /**
  33890. * Abstract class used to provide common services for all typed geometries
  33891. */
  33892. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33893. __extends(_PrimitiveGeometry, _super);
  33894. /**
  33895. * Creates a new typed geometry
  33896. * @param id defines the unique ID of the geometry
  33897. * @param scene defines the hosting scene
  33898. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33899. * @param mesh defines the hosting mesh (can be null)
  33900. */
  33901. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33902. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33903. if (mesh === void 0) { mesh = null; }
  33904. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33905. _this._canBeRegenerated = _canBeRegenerated;
  33906. _this._beingRegenerated = true;
  33907. _this.regenerate();
  33908. _this._beingRegenerated = false;
  33909. return _this;
  33910. }
  33911. /**
  33912. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33913. * @returns true if the geometry can be regenerated
  33914. */
  33915. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33916. return this._canBeRegenerated;
  33917. };
  33918. /**
  33919. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33920. */
  33921. _PrimitiveGeometry.prototype.regenerate = function () {
  33922. if (!this._canBeRegenerated) {
  33923. return;
  33924. }
  33925. this._beingRegenerated = true;
  33926. this.setAllVerticesData(this._regenerateVertexData(), false);
  33927. this._beingRegenerated = false;
  33928. };
  33929. /**
  33930. * Clone the geometry
  33931. * @param id defines the unique ID of the new geometry
  33932. * @returns the new geometry
  33933. */
  33934. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33935. return _super.prototype.copy.call(this, id);
  33936. };
  33937. // overrides
  33938. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33939. if (!this._beingRegenerated) {
  33940. return;
  33941. }
  33942. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33943. };
  33944. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33945. if (!this._beingRegenerated) {
  33946. return;
  33947. }
  33948. _super.prototype.setVerticesData.call(this, kind, data, false);
  33949. };
  33950. // to override
  33951. /** @ignore */
  33952. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33953. throw new Error("Abstract method");
  33954. };
  33955. _PrimitiveGeometry.prototype.copy = function (id) {
  33956. throw new Error("Must be overriden in sub-classes.");
  33957. };
  33958. _PrimitiveGeometry.prototype.serialize = function () {
  33959. var serializationObject = _super.prototype.serialize.call(this);
  33960. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33961. return serializationObject;
  33962. };
  33963. return _PrimitiveGeometry;
  33964. }(Geometry));
  33965. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33966. /**
  33967. * Creates a ribbon geometry
  33968. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33969. */
  33970. var RibbonGeometry = /** @class */ (function (_super) {
  33971. __extends(RibbonGeometry, _super);
  33972. /**
  33973. * Creates a ribbon geometry
  33974. * @param id defines the unique ID of the geometry
  33975. * @param scene defines the hosting scene
  33976. * @param pathArray defines the array of paths to use
  33977. * @param closeArray defines if the last path and the first path must be joined
  33978. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33979. * @param offset defines the offset between points
  33980. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33981. * @param mesh defines the hosting mesh (can be null)
  33982. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33983. */
  33984. function RibbonGeometry(id, scene,
  33985. /**
  33986. * Defines the array of paths to use
  33987. */
  33988. pathArray,
  33989. /**
  33990. * Defines if the last and first points of each path in your pathArray must be joined
  33991. */
  33992. closeArray,
  33993. /**
  33994. * Defines if the last and first points of each path in your pathArray must be joined
  33995. */
  33996. closePath,
  33997. /**
  33998. * Defines the offset between points
  33999. */
  34000. offset, canBeRegenerated, mesh,
  34001. /**
  34002. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34003. */
  34004. side) {
  34005. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34006. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34007. _this.pathArray = pathArray;
  34008. _this.closeArray = closeArray;
  34009. _this.closePath = closePath;
  34010. _this.offset = offset;
  34011. _this.side = side;
  34012. return _this;
  34013. }
  34014. /** @ignore */
  34015. RibbonGeometry.prototype._regenerateVertexData = function () {
  34016. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  34017. };
  34018. RibbonGeometry.prototype.copy = function (id) {
  34019. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  34020. };
  34021. return RibbonGeometry;
  34022. }(_PrimitiveGeometry));
  34023. BABYLON.RibbonGeometry = RibbonGeometry;
  34024. /**
  34025. * Creates a box geometry
  34026. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  34027. */
  34028. var BoxGeometry = /** @class */ (function (_super) {
  34029. __extends(BoxGeometry, _super);
  34030. /**
  34031. * Creates a box geometry
  34032. * @param id defines the unique ID of the geometry
  34033. * @param scene defines the hosting scene
  34034. * @param size defines the zise of the box (width, height and depth are the same)
  34035. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34036. * @param mesh defines the hosting mesh (can be null)
  34037. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34038. */
  34039. function BoxGeometry(id, scene,
  34040. /**
  34041. * Defines the zise of the box (width, height and depth are the same)
  34042. */
  34043. size, canBeRegenerated, mesh,
  34044. /**
  34045. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34046. */
  34047. side) {
  34048. if (mesh === void 0) { mesh = null; }
  34049. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34050. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34051. _this.size = size;
  34052. _this.side = side;
  34053. return _this;
  34054. }
  34055. BoxGeometry.prototype._regenerateVertexData = function () {
  34056. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  34057. };
  34058. BoxGeometry.prototype.copy = function (id) {
  34059. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  34060. };
  34061. BoxGeometry.prototype.serialize = function () {
  34062. var serializationObject = _super.prototype.serialize.call(this);
  34063. serializationObject.size = this.size;
  34064. return serializationObject;
  34065. };
  34066. BoxGeometry.Parse = function (parsedBox, scene) {
  34067. if (scene.getGeometryByID(parsedBox.id)) {
  34068. return null; // null since geometry could be something else than a box...
  34069. }
  34070. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  34071. if (BABYLON.Tags) {
  34072. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  34073. }
  34074. scene.pushGeometry(box, true);
  34075. return box;
  34076. };
  34077. return BoxGeometry;
  34078. }(_PrimitiveGeometry));
  34079. BABYLON.BoxGeometry = BoxGeometry;
  34080. /**
  34081. * Creates a sphere geometry
  34082. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  34083. */
  34084. var SphereGeometry = /** @class */ (function (_super) {
  34085. __extends(SphereGeometry, _super);
  34086. /**
  34087. * Create a new sphere geometry
  34088. * @param id defines the unique ID of the geometry
  34089. * @param scene defines the hosting scene
  34090. * @param segments defines the number of segments to use to create the sphere
  34091. * @param diameter defines the diameter of the sphere
  34092. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34093. * @param mesh defines the hosting mesh (can be null)
  34094. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34095. */
  34096. function SphereGeometry(id, scene,
  34097. /**
  34098. * Defines the number of segments to use to create the sphere
  34099. */
  34100. segments,
  34101. /**
  34102. * Defines the diameter of the sphere
  34103. */
  34104. diameter, canBeRegenerated, mesh,
  34105. /**
  34106. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34107. */
  34108. side) {
  34109. if (mesh === void 0) { mesh = null; }
  34110. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34111. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34112. _this.segments = segments;
  34113. _this.diameter = diameter;
  34114. _this.side = side;
  34115. return _this;
  34116. }
  34117. SphereGeometry.prototype._regenerateVertexData = function () {
  34118. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  34119. };
  34120. SphereGeometry.prototype.copy = function (id) {
  34121. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  34122. };
  34123. SphereGeometry.prototype.serialize = function () {
  34124. var serializationObject = _super.prototype.serialize.call(this);
  34125. serializationObject.segments = this.segments;
  34126. serializationObject.diameter = this.diameter;
  34127. return serializationObject;
  34128. };
  34129. SphereGeometry.Parse = function (parsedSphere, scene) {
  34130. if (scene.getGeometryByID(parsedSphere.id)) {
  34131. return null; // null since geometry could be something else than a sphere...
  34132. }
  34133. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34134. if (BABYLON.Tags) {
  34135. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34136. }
  34137. scene.pushGeometry(sphere, true);
  34138. return sphere;
  34139. };
  34140. return SphereGeometry;
  34141. }(_PrimitiveGeometry));
  34142. BABYLON.SphereGeometry = SphereGeometry;
  34143. /**
  34144. * Creates a disc geometry
  34145. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  34146. */
  34147. var DiscGeometry = /** @class */ (function (_super) {
  34148. __extends(DiscGeometry, _super);
  34149. /**
  34150. * Creates a new disc geometry
  34151. * @param id defines the unique ID of the geometry
  34152. * @param scene defines the hosting scene
  34153. * @param radius defines the radius of the disc
  34154. * @param tessellation defines the tesselation factor to apply to the disc
  34155. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34156. * @param mesh defines the hosting mesh (can be null)
  34157. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34158. */
  34159. function DiscGeometry(id, scene,
  34160. /**
  34161. * Defines the radius of the disc
  34162. */
  34163. radius,
  34164. /**
  34165. * Defines the tesselation factor to apply to the disc
  34166. */
  34167. tessellation, canBeRegenerated, mesh,
  34168. /**
  34169. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34170. */
  34171. side) {
  34172. if (mesh === void 0) { mesh = null; }
  34173. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34174. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34175. _this.radius = radius;
  34176. _this.tessellation = tessellation;
  34177. _this.side = side;
  34178. return _this;
  34179. }
  34180. DiscGeometry.prototype._regenerateVertexData = function () {
  34181. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34182. };
  34183. DiscGeometry.prototype.copy = function (id) {
  34184. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34185. };
  34186. return DiscGeometry;
  34187. }(_PrimitiveGeometry));
  34188. BABYLON.DiscGeometry = DiscGeometry;
  34189. /**
  34190. * Creates a new cylinder geometry
  34191. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  34192. */
  34193. var CylinderGeometry = /** @class */ (function (_super) {
  34194. __extends(CylinderGeometry, _super);
  34195. /**
  34196. * Creates a new cylinder geometry
  34197. * @param id defines the unique ID of the geometry
  34198. * @param scene defines the hosting scene
  34199. * @param height defines the height of the cylinder
  34200. * @param diameterTop defines the diameter of the cylinder's top cap
  34201. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  34202. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  34203. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  34204. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34205. * @param mesh defines the hosting mesh (can be null)
  34206. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34207. */
  34208. function CylinderGeometry(id, scene,
  34209. /**
  34210. * Defines the height of the cylinder
  34211. */
  34212. height,
  34213. /**
  34214. * Defines the diameter of the cylinder's top cap
  34215. */
  34216. diameterTop,
  34217. /**
  34218. * Defines the diameter of the cylinder's bottom cap
  34219. */
  34220. diameterBottom,
  34221. /**
  34222. * Defines the tessellation factor to apply to the cylinder
  34223. */
  34224. tessellation,
  34225. /**
  34226. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  34227. */
  34228. subdivisions, canBeRegenerated, mesh,
  34229. /**
  34230. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34231. */
  34232. side) {
  34233. if (subdivisions === void 0) { subdivisions = 1; }
  34234. if (mesh === void 0) { mesh = null; }
  34235. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34236. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34237. _this.height = height;
  34238. _this.diameterTop = diameterTop;
  34239. _this.diameterBottom = diameterBottom;
  34240. _this.tessellation = tessellation;
  34241. _this.subdivisions = subdivisions;
  34242. _this.side = side;
  34243. return _this;
  34244. }
  34245. CylinderGeometry.prototype._regenerateVertexData = function () {
  34246. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34247. };
  34248. CylinderGeometry.prototype.copy = function (id) {
  34249. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34250. };
  34251. CylinderGeometry.prototype.serialize = function () {
  34252. var serializationObject = _super.prototype.serialize.call(this);
  34253. serializationObject.height = this.height;
  34254. serializationObject.diameterTop = this.diameterTop;
  34255. serializationObject.diameterBottom = this.diameterBottom;
  34256. serializationObject.tessellation = this.tessellation;
  34257. return serializationObject;
  34258. };
  34259. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  34260. if (scene.getGeometryByID(parsedCylinder.id)) {
  34261. return null; // null since geometry could be something else than a cylinder...
  34262. }
  34263. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34264. if (BABYLON.Tags) {
  34265. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34266. }
  34267. scene.pushGeometry(cylinder, true);
  34268. return cylinder;
  34269. };
  34270. return CylinderGeometry;
  34271. }(_PrimitiveGeometry));
  34272. BABYLON.CylinderGeometry = CylinderGeometry;
  34273. /**
  34274. * Creates a new torus geometry
  34275. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  34276. */
  34277. var TorusGeometry = /** @class */ (function (_super) {
  34278. __extends(TorusGeometry, _super);
  34279. /**
  34280. * Creates a new torus geometry
  34281. * @param id defines the unique ID of the geometry
  34282. * @param scene defines the hosting scene
  34283. * @param diameter defines the diameter of the torus
  34284. * @param thickness defines the thickness of the torus (ie. internal diameter)
  34285. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  34286. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34287. * @param mesh defines the hosting mesh (can be null)
  34288. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34289. */
  34290. function TorusGeometry(id, scene,
  34291. /**
  34292. * Defines the diameter of the torus
  34293. */
  34294. diameter,
  34295. /**
  34296. * Defines the thickness of the torus (ie. internal diameter)
  34297. */
  34298. thickness,
  34299. /**
  34300. * Defines the tesselation factor to apply to the torus
  34301. */
  34302. tessellation, canBeRegenerated, mesh,
  34303. /**
  34304. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34305. */
  34306. side) {
  34307. if (mesh === void 0) { mesh = null; }
  34308. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34309. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34310. _this.diameter = diameter;
  34311. _this.thickness = thickness;
  34312. _this.tessellation = tessellation;
  34313. _this.side = side;
  34314. return _this;
  34315. }
  34316. TorusGeometry.prototype._regenerateVertexData = function () {
  34317. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34318. };
  34319. TorusGeometry.prototype.copy = function (id) {
  34320. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34321. };
  34322. TorusGeometry.prototype.serialize = function () {
  34323. var serializationObject = _super.prototype.serialize.call(this);
  34324. serializationObject.diameter = this.diameter;
  34325. serializationObject.thickness = this.thickness;
  34326. serializationObject.tessellation = this.tessellation;
  34327. return serializationObject;
  34328. };
  34329. TorusGeometry.Parse = function (parsedTorus, scene) {
  34330. if (scene.getGeometryByID(parsedTorus.id)) {
  34331. return null; // null since geometry could be something else than a torus...
  34332. }
  34333. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34334. if (BABYLON.Tags) {
  34335. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34336. }
  34337. scene.pushGeometry(torus, true);
  34338. return torus;
  34339. };
  34340. return TorusGeometry;
  34341. }(_PrimitiveGeometry));
  34342. BABYLON.TorusGeometry = TorusGeometry;
  34343. /**
  34344. * Creates a new ground geometry
  34345. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  34346. */
  34347. var GroundGeometry = /** @class */ (function (_super) {
  34348. __extends(GroundGeometry, _super);
  34349. /**
  34350. * Creates a new ground geometry
  34351. * @param id defines the unique ID of the geometry
  34352. * @param scene defines the hosting scene
  34353. * @param width defines the width of the ground
  34354. * @param height defines the height of the ground
  34355. * @param subdivisions defines the subdivisions to apply to the ground
  34356. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34357. * @param mesh defines the hosting mesh (can be null)
  34358. */
  34359. function GroundGeometry(id, scene,
  34360. /**
  34361. * Defines the width of the ground
  34362. */
  34363. width,
  34364. /**
  34365. * Defines the height of the ground
  34366. */
  34367. height,
  34368. /**
  34369. * Defines the subdivisions to apply to the ground
  34370. */
  34371. subdivisions, canBeRegenerated, mesh) {
  34372. if (mesh === void 0) { mesh = null; }
  34373. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34374. _this.width = width;
  34375. _this.height = height;
  34376. _this.subdivisions = subdivisions;
  34377. return _this;
  34378. }
  34379. GroundGeometry.prototype._regenerateVertexData = function () {
  34380. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34381. };
  34382. GroundGeometry.prototype.copy = function (id) {
  34383. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34384. };
  34385. GroundGeometry.prototype.serialize = function () {
  34386. var serializationObject = _super.prototype.serialize.call(this);
  34387. serializationObject.width = this.width;
  34388. serializationObject.height = this.height;
  34389. serializationObject.subdivisions = this.subdivisions;
  34390. return serializationObject;
  34391. };
  34392. GroundGeometry.Parse = function (parsedGround, scene) {
  34393. if (scene.getGeometryByID(parsedGround.id)) {
  34394. return null; // null since geometry could be something else than a ground...
  34395. }
  34396. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34397. if (BABYLON.Tags) {
  34398. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34399. }
  34400. scene.pushGeometry(ground, true);
  34401. return ground;
  34402. };
  34403. return GroundGeometry;
  34404. }(_PrimitiveGeometry));
  34405. BABYLON.GroundGeometry = GroundGeometry;
  34406. /**
  34407. * Creates a tiled ground geometry
  34408. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  34409. */
  34410. var TiledGroundGeometry = /** @class */ (function (_super) {
  34411. __extends(TiledGroundGeometry, _super);
  34412. /**
  34413. * Creates a tiled ground geometry
  34414. * @param id defines the unique ID of the geometry
  34415. * @param scene defines the hosting scene
  34416. * @param xmin defines the minimum value on X axis
  34417. * @param zmin defines the minimum value on Z axis
  34418. * @param xmax defines the maximum value on X axis
  34419. * @param zmax defines the maximum value on Z axis
  34420. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  34421. * @param precision defines the precision to use when computing the tiles
  34422. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34423. * @param mesh defines the hosting mesh (can be null)
  34424. */
  34425. function TiledGroundGeometry(id, scene,
  34426. /**
  34427. * Defines the minimum value on X axis
  34428. */
  34429. xmin,
  34430. /**
  34431. * Defines the minimum value on Z axis
  34432. */
  34433. zmin,
  34434. /**
  34435. * Defines the maximum value on X axis
  34436. */
  34437. xmax,
  34438. /**
  34439. * Defines the maximum value on Z axis
  34440. */
  34441. zmax,
  34442. /**
  34443. * Defines the subdivisions to apply to the ground
  34444. */
  34445. subdivisions,
  34446. /**
  34447. * Defines the precision to use when computing the tiles
  34448. */
  34449. precision, canBeRegenerated, mesh) {
  34450. if (mesh === void 0) { mesh = null; }
  34451. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34452. _this.xmin = xmin;
  34453. _this.zmin = zmin;
  34454. _this.xmax = xmax;
  34455. _this.zmax = zmax;
  34456. _this.subdivisions = subdivisions;
  34457. _this.precision = precision;
  34458. return _this;
  34459. }
  34460. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  34461. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34462. };
  34463. TiledGroundGeometry.prototype.copy = function (id) {
  34464. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34465. };
  34466. return TiledGroundGeometry;
  34467. }(_PrimitiveGeometry));
  34468. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  34469. /**
  34470. * Creates a plane geometry
  34471. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  34472. */
  34473. var PlaneGeometry = /** @class */ (function (_super) {
  34474. __extends(PlaneGeometry, _super);
  34475. /**
  34476. * Creates a plane geometry
  34477. * @param id defines the unique ID of the geometry
  34478. * @param scene defines the hosting scene
  34479. * @param size defines the size of the plane (width === height)
  34480. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34481. * @param mesh defines the hosting mesh (can be null)
  34482. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34483. */
  34484. function PlaneGeometry(id, scene,
  34485. /**
  34486. * Defines the size of the plane (width === height)
  34487. */
  34488. size, canBeRegenerated, mesh,
  34489. /**
  34490. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34491. */
  34492. side) {
  34493. if (mesh === void 0) { mesh = null; }
  34494. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34495. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34496. _this.size = size;
  34497. _this.side = side;
  34498. return _this;
  34499. }
  34500. PlaneGeometry.prototype._regenerateVertexData = function () {
  34501. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34502. };
  34503. PlaneGeometry.prototype.copy = function (id) {
  34504. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34505. };
  34506. PlaneGeometry.prototype.serialize = function () {
  34507. var serializationObject = _super.prototype.serialize.call(this);
  34508. serializationObject.size = this.size;
  34509. return serializationObject;
  34510. };
  34511. PlaneGeometry.Parse = function (parsedPlane, scene) {
  34512. if (scene.getGeometryByID(parsedPlane.id)) {
  34513. return null; // null since geometry could be something else than a ground...
  34514. }
  34515. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34516. if (BABYLON.Tags) {
  34517. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34518. }
  34519. scene.pushGeometry(plane, true);
  34520. return plane;
  34521. };
  34522. return PlaneGeometry;
  34523. }(_PrimitiveGeometry));
  34524. BABYLON.PlaneGeometry = PlaneGeometry;
  34525. /**
  34526. * Creates a torus knot geometry
  34527. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  34528. */
  34529. var TorusKnotGeometry = /** @class */ (function (_super) {
  34530. __extends(TorusKnotGeometry, _super);
  34531. /**
  34532. * Creates a torus knot geometry
  34533. * @param id defines the unique ID of the geometry
  34534. * @param scene defines the hosting scene
  34535. * @param radius defines the radius of the torus knot
  34536. * @param tube defines the thickness of the torus knot tube
  34537. * @param radialSegments defines the number of radial segments
  34538. * @param tubularSegments defines the number of tubular segments
  34539. * @param p defines the first number of windings
  34540. * @param q defines the second number of windings
  34541. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34542. * @param mesh defines the hosting mesh (can be null)
  34543. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34544. */
  34545. function TorusKnotGeometry(id, scene,
  34546. /**
  34547. * Defines the radius of the torus knot
  34548. */
  34549. radius,
  34550. /**
  34551. * Defines the thickness of the torus knot tube
  34552. */
  34553. tube,
  34554. /**
  34555. * Defines the number of radial segments
  34556. */
  34557. radialSegments,
  34558. /**
  34559. * Defines the number of tubular segments
  34560. */
  34561. tubularSegments,
  34562. /**
  34563. * Defines the first number of windings
  34564. */
  34565. p,
  34566. /**
  34567. * Defines the second number of windings
  34568. */
  34569. q, canBeRegenerated, mesh,
  34570. /**
  34571. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34572. */
  34573. side) {
  34574. if (mesh === void 0) { mesh = null; }
  34575. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34576. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34577. _this.radius = radius;
  34578. _this.tube = tube;
  34579. _this.radialSegments = radialSegments;
  34580. _this.tubularSegments = tubularSegments;
  34581. _this.p = p;
  34582. _this.q = q;
  34583. _this.side = side;
  34584. return _this;
  34585. }
  34586. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  34587. 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 });
  34588. };
  34589. TorusKnotGeometry.prototype.copy = function (id) {
  34590. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34591. };
  34592. TorusKnotGeometry.prototype.serialize = function () {
  34593. var serializationObject = _super.prototype.serialize.call(this);
  34594. serializationObject.radius = this.radius;
  34595. serializationObject.tube = this.tube;
  34596. serializationObject.radialSegments = this.radialSegments;
  34597. serializationObject.tubularSegments = this.tubularSegments;
  34598. serializationObject.p = this.p;
  34599. serializationObject.q = this.q;
  34600. return serializationObject;
  34601. };
  34602. ;
  34603. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  34604. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34605. return null; // null since geometry could be something else than a ground...
  34606. }
  34607. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34608. if (BABYLON.Tags) {
  34609. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34610. }
  34611. scene.pushGeometry(torusKnot, true);
  34612. return torusKnot;
  34613. };
  34614. return TorusKnotGeometry;
  34615. }(_PrimitiveGeometry));
  34616. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  34617. //}
  34618. })(BABYLON || (BABYLON = {}));
  34619. //# sourceMappingURL=babylon.geometry.js.map
  34620. var BABYLON;
  34621. (function (BABYLON) {
  34622. /**
  34623. * PostProcessManager is used to manage one or more post processes or post process pipelines
  34624. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  34625. */
  34626. var PostProcessManager = /** @class */ (function () {
  34627. /**
  34628. * Creates a new instance of @see PostProcess
  34629. * @param scene The scene that the post process is associated with.
  34630. */
  34631. function PostProcessManager(scene) {
  34632. this._vertexBuffers = {};
  34633. this._scene = scene;
  34634. }
  34635. PostProcessManager.prototype._prepareBuffers = function () {
  34636. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34637. return;
  34638. }
  34639. // VBO
  34640. var vertices = [];
  34641. vertices.push(1, 1);
  34642. vertices.push(-1, 1);
  34643. vertices.push(-1, -1);
  34644. vertices.push(1, -1);
  34645. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34646. this._buildIndexBuffer();
  34647. };
  34648. PostProcessManager.prototype._buildIndexBuffer = function () {
  34649. // Indices
  34650. var indices = [];
  34651. indices.push(0);
  34652. indices.push(1);
  34653. indices.push(2);
  34654. indices.push(0);
  34655. indices.push(2);
  34656. indices.push(3);
  34657. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34658. };
  34659. /**
  34660. * Rebuilds the vertex buffers of the manager.
  34661. */
  34662. PostProcessManager.prototype._rebuild = function () {
  34663. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34664. if (!vb) {
  34665. return;
  34666. }
  34667. vb._rebuild();
  34668. this._buildIndexBuffer();
  34669. };
  34670. // Methods
  34671. /**
  34672. * Prepares a frame to be run through a post process.
  34673. * @param sourceTexture The input texture to the post procesess. (default: null)
  34674. * @param postProcesses An array of post processes to be run. (default: null)
  34675. * @returns True if the post processes were able to be run.
  34676. */
  34677. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  34678. if (sourceTexture === void 0) { sourceTexture = null; }
  34679. if (postProcesses === void 0) { postProcesses = null; }
  34680. var camera = this._scene.activeCamera;
  34681. if (!camera) {
  34682. return false;
  34683. }
  34684. var postProcesses = postProcesses || camera._postProcesses;
  34685. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34686. return false;
  34687. }
  34688. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  34689. return true;
  34690. };
  34691. /**
  34692. * Manually render a set of post processes to a texture.
  34693. * @param postProcesses An array of post processes to be run.
  34694. * @param targetTexture The target texture to render to.
  34695. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  34696. */
  34697. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  34698. if (targetTexture === void 0) { targetTexture = null; }
  34699. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34700. var engine = this._scene.getEngine();
  34701. for (var index = 0; index < postProcesses.length; index++) {
  34702. if (index < postProcesses.length - 1) {
  34703. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34704. }
  34705. else {
  34706. if (targetTexture) {
  34707. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  34708. }
  34709. else {
  34710. engine.restoreDefaultFramebuffer();
  34711. }
  34712. }
  34713. var pp = postProcesses[index];
  34714. var effect = pp.apply();
  34715. if (effect) {
  34716. pp.onBeforeRenderObservable.notifyObservers(effect);
  34717. // VBOs
  34718. this._prepareBuffers();
  34719. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34720. // Draw order
  34721. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34722. pp.onAfterRenderObservable.notifyObservers(effect);
  34723. }
  34724. }
  34725. // Restore depth buffer
  34726. engine.setDepthBuffer(true);
  34727. engine.setDepthWrite(true);
  34728. };
  34729. /**
  34730. * Finalize the result of the output of the postprocesses.
  34731. * @param doNotPresent If true the result will not be displayed to the screen.
  34732. * @param targetTexture The target texture to render to.
  34733. * @param faceIndex The index of the face to bind the target texture to.
  34734. * @param postProcesses The array of post processes to render.
  34735. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  34736. */
  34737. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  34738. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34739. var camera = this._scene.activeCamera;
  34740. if (!camera) {
  34741. return;
  34742. }
  34743. postProcesses = postProcesses || camera._postProcesses;
  34744. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34745. return;
  34746. }
  34747. var engine = this._scene.getEngine();
  34748. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34749. if (index < len - 1) {
  34750. postProcesses[index + 1].activate(camera, targetTexture);
  34751. }
  34752. else {
  34753. if (targetTexture) {
  34754. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  34755. }
  34756. else {
  34757. engine.restoreDefaultFramebuffer();
  34758. }
  34759. }
  34760. if (doNotPresent) {
  34761. break;
  34762. }
  34763. var pp = postProcesses[index];
  34764. var effect = pp.apply();
  34765. if (effect) {
  34766. pp.onBeforeRenderObservable.notifyObservers(effect);
  34767. // VBOs
  34768. this._prepareBuffers();
  34769. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34770. // Draw order
  34771. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34772. pp.onAfterRenderObservable.notifyObservers(effect);
  34773. }
  34774. }
  34775. // Restore states
  34776. engine.setDepthBuffer(true);
  34777. engine.setDepthWrite(true);
  34778. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34779. };
  34780. /**
  34781. * Disposes of the post process manager.
  34782. */
  34783. PostProcessManager.prototype.dispose = function () {
  34784. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34785. if (buffer) {
  34786. buffer.dispose();
  34787. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34788. }
  34789. if (this._indexBuffer) {
  34790. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34791. this._indexBuffer = null;
  34792. }
  34793. };
  34794. return PostProcessManager;
  34795. }());
  34796. BABYLON.PostProcessManager = PostProcessManager;
  34797. })(BABYLON || (BABYLON = {}));
  34798. //# sourceMappingURL=babylon.postProcessManager.js.map
  34799. var BABYLON;
  34800. (function (BABYLON) {
  34801. /**
  34802. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  34803. */
  34804. var PerformanceMonitor = /** @class */ (function () {
  34805. /**
  34806. * constructor
  34807. * @param frameSampleSize The number of samples required to saturate the sliding window
  34808. */
  34809. function PerformanceMonitor(frameSampleSize) {
  34810. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  34811. this._enabled = true;
  34812. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  34813. }
  34814. /**
  34815. * Samples current frame
  34816. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34817. */
  34818. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34819. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34820. if (!this._enabled)
  34821. return;
  34822. if (this._lastFrameTimeMs != null) {
  34823. var dt = timeMs - this._lastFrameTimeMs;
  34824. this._rollingFrameTime.add(dt);
  34825. }
  34826. this._lastFrameTimeMs = timeMs;
  34827. };
  34828. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34829. /**
  34830. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34831. * @return Average frame time in milliseconds
  34832. */
  34833. get: function () {
  34834. return this._rollingFrameTime.average;
  34835. },
  34836. enumerable: true,
  34837. configurable: true
  34838. });
  34839. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34840. /**
  34841. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34842. * @return Frame time variance in milliseconds squared
  34843. */
  34844. get: function () {
  34845. return this._rollingFrameTime.variance;
  34846. },
  34847. enumerable: true,
  34848. configurable: true
  34849. });
  34850. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34851. /**
  34852. * Returns the frame time of the most recent frame
  34853. * @return Frame time in milliseconds
  34854. */
  34855. get: function () {
  34856. return this._rollingFrameTime.history(0);
  34857. },
  34858. enumerable: true,
  34859. configurable: true
  34860. });
  34861. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34862. /**
  34863. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34864. * @return Framerate in frames per second
  34865. */
  34866. get: function () {
  34867. return 1000.0 / this._rollingFrameTime.average;
  34868. },
  34869. enumerable: true,
  34870. configurable: true
  34871. });
  34872. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34873. /**
  34874. * Returns the average framerate in frames per second using the most recent frame time
  34875. * @return Framerate in frames per second
  34876. */
  34877. get: function () {
  34878. var history = this._rollingFrameTime.history(0);
  34879. if (history === 0) {
  34880. return 0;
  34881. }
  34882. return 1000.0 / history;
  34883. },
  34884. enumerable: true,
  34885. configurable: true
  34886. });
  34887. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34888. /**
  34889. * Returns true if enough samples have been taken to completely fill the sliding window
  34890. * @return true if saturated
  34891. */
  34892. get: function () {
  34893. return this._rollingFrameTime.isSaturated();
  34894. },
  34895. enumerable: true,
  34896. configurable: true
  34897. });
  34898. /**
  34899. * Enables contributions to the sliding window sample set
  34900. */
  34901. PerformanceMonitor.prototype.enable = function () {
  34902. this._enabled = true;
  34903. };
  34904. /**
  34905. * Disables contributions to the sliding window sample set
  34906. * Samples will not be interpolated over the disabled period
  34907. */
  34908. PerformanceMonitor.prototype.disable = function () {
  34909. this._enabled = false;
  34910. //clear last sample to avoid interpolating over the disabled period when next enabled
  34911. this._lastFrameTimeMs = null;
  34912. };
  34913. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34914. /**
  34915. * Returns true if sampling is enabled
  34916. * @return true if enabled
  34917. */
  34918. get: function () {
  34919. return this._enabled;
  34920. },
  34921. enumerable: true,
  34922. configurable: true
  34923. });
  34924. /**
  34925. * Resets performance monitor
  34926. */
  34927. PerformanceMonitor.prototype.reset = function () {
  34928. //clear last sample to avoid interpolating over the disabled period when next enabled
  34929. this._lastFrameTimeMs = null;
  34930. //wipe record
  34931. this._rollingFrameTime.reset();
  34932. };
  34933. return PerformanceMonitor;
  34934. }());
  34935. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34936. /**
  34937. * RollingAverage
  34938. *
  34939. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34940. */
  34941. var RollingAverage = /** @class */ (function () {
  34942. /**
  34943. * constructor
  34944. * @param length The number of samples required to saturate the sliding window
  34945. */
  34946. function RollingAverage(length) {
  34947. this._samples = new Array(length);
  34948. this.reset();
  34949. }
  34950. /**
  34951. * Adds a sample to the sample set
  34952. * @param v The sample value
  34953. */
  34954. RollingAverage.prototype.add = function (v) {
  34955. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34956. var delta;
  34957. //we need to check if we've already wrapped round
  34958. if (this.isSaturated()) {
  34959. //remove bottom of stack from mean
  34960. var bottomValue = this._samples[this._pos];
  34961. delta = bottomValue - this.average;
  34962. this.average -= delta / (this._sampleCount - 1);
  34963. this._m2 -= delta * (bottomValue - this.average);
  34964. }
  34965. else {
  34966. this._sampleCount++;
  34967. }
  34968. //add new value to mean
  34969. delta = v - this.average;
  34970. this.average += delta / (this._sampleCount);
  34971. this._m2 += delta * (v - this.average);
  34972. //set the new variance
  34973. this.variance = this._m2 / (this._sampleCount - 1);
  34974. this._samples[this._pos] = v;
  34975. this._pos++;
  34976. this._pos %= this._samples.length; //positive wrap around
  34977. };
  34978. /**
  34979. * Returns previously added values or null if outside of history or outside the sliding window domain
  34980. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34981. * @return Value previously recorded with add() or null if outside of range
  34982. */
  34983. RollingAverage.prototype.history = function (i) {
  34984. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34985. return 0;
  34986. }
  34987. var i0 = this._wrapPosition(this._pos - 1.0);
  34988. return this._samples[this._wrapPosition(i0 - i)];
  34989. };
  34990. /**
  34991. * Returns true if enough samples have been taken to completely fill the sliding window
  34992. * @return true if sample-set saturated
  34993. */
  34994. RollingAverage.prototype.isSaturated = function () {
  34995. return this._sampleCount >= this._samples.length;
  34996. };
  34997. /**
  34998. * Resets the rolling average (equivalent to 0 samples taken so far)
  34999. */
  35000. RollingAverage.prototype.reset = function () {
  35001. this.average = 0;
  35002. this.variance = 0;
  35003. this._sampleCount = 0;
  35004. this._pos = 0;
  35005. this._m2 = 0;
  35006. };
  35007. /**
  35008. * Wraps a value around the sample range boundaries
  35009. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  35010. * @return Wrapped position in sample range
  35011. */
  35012. RollingAverage.prototype._wrapPosition = function (i) {
  35013. var max = this._samples.length;
  35014. return ((i % max) + max) % max;
  35015. };
  35016. return RollingAverage;
  35017. }());
  35018. BABYLON.RollingAverage = RollingAverage;
  35019. })(BABYLON || (BABYLON = {}));
  35020. //# sourceMappingURL=babylon.performanceMonitor.js.map
  35021. var BABYLON;
  35022. (function (BABYLON) {
  35023. /**
  35024. * This groups together the common properties used for image processing either in direct forward pass
  35025. * or through post processing effect depending on the use of the image processing pipeline in your scene
  35026. * or not.
  35027. */
  35028. var ImageProcessingConfiguration = /** @class */ (function () {
  35029. function ImageProcessingConfiguration() {
  35030. /**
  35031. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  35032. */
  35033. this.colorCurves = new BABYLON.ColorCurves();
  35034. this._colorCurvesEnabled = false;
  35035. this._colorGradingEnabled = false;
  35036. this._colorGradingWithGreenDepth = true;
  35037. this._colorGradingBGR = true;
  35038. this._exposure = 1.0;
  35039. this._toneMappingEnabled = false;
  35040. this._contrast = 1.0;
  35041. /**
  35042. * Vignette stretch size.
  35043. */
  35044. this.vignetteStretch = 0;
  35045. /**
  35046. * Vignette centre X Offset.
  35047. */
  35048. this.vignetteCentreX = 0;
  35049. /**
  35050. * Vignette centre Y Offset.
  35051. */
  35052. this.vignetteCentreY = 0;
  35053. /**
  35054. * Vignette weight or intensity of the vignette effect.
  35055. */
  35056. this.vignetteWeight = 1.5;
  35057. /**
  35058. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  35059. * if vignetteEnabled is set to true.
  35060. */
  35061. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  35062. /**
  35063. * Camera field of view used by the Vignette effect.
  35064. */
  35065. this.vignetteCameraFov = 0.5;
  35066. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  35067. this._vignetteEnabled = false;
  35068. this._applyByPostProcess = false;
  35069. this._isEnabled = true;
  35070. /**
  35071. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  35072. * @type {BABYLON.Observable}
  35073. */
  35074. this.onUpdateParameters = new BABYLON.Observable();
  35075. }
  35076. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  35077. /**
  35078. * Gets wether the color curves effect is enabled.
  35079. */
  35080. get: function () {
  35081. return this._colorCurvesEnabled;
  35082. },
  35083. /**
  35084. * Sets wether the color curves effect is enabled.
  35085. */
  35086. set: function (value) {
  35087. if (this._colorCurvesEnabled === value) {
  35088. return;
  35089. }
  35090. this._colorCurvesEnabled = value;
  35091. this._updateParameters();
  35092. },
  35093. enumerable: true,
  35094. configurable: true
  35095. });
  35096. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  35097. /**
  35098. * Gets wether the color grading effect is enabled.
  35099. */
  35100. get: function () {
  35101. return this._colorGradingEnabled;
  35102. },
  35103. /**
  35104. * Sets wether the color grading effect is enabled.
  35105. */
  35106. set: function (value) {
  35107. if (this._colorGradingEnabled === value) {
  35108. return;
  35109. }
  35110. this._colorGradingEnabled = value;
  35111. this._updateParameters();
  35112. },
  35113. enumerable: true,
  35114. configurable: true
  35115. });
  35116. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  35117. /**
  35118. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  35119. */
  35120. get: function () {
  35121. return this._colorGradingWithGreenDepth;
  35122. },
  35123. /**
  35124. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  35125. */
  35126. set: function (value) {
  35127. if (this._colorGradingWithGreenDepth === value) {
  35128. return;
  35129. }
  35130. this._colorGradingWithGreenDepth = value;
  35131. this._updateParameters();
  35132. },
  35133. enumerable: true,
  35134. configurable: true
  35135. });
  35136. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  35137. /**
  35138. * Gets wether the color grading texture contains BGR values.
  35139. */
  35140. get: function () {
  35141. return this._colorGradingBGR;
  35142. },
  35143. /**
  35144. * Sets wether the color grading texture contains BGR values.
  35145. */
  35146. set: function (value) {
  35147. if (this._colorGradingBGR === value) {
  35148. return;
  35149. }
  35150. this._colorGradingBGR = value;
  35151. this._updateParameters();
  35152. },
  35153. enumerable: true,
  35154. configurable: true
  35155. });
  35156. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  35157. /**
  35158. * Gets the Exposure used in the effect.
  35159. */
  35160. get: function () {
  35161. return this._exposure;
  35162. },
  35163. /**
  35164. * Sets the Exposure used in the effect.
  35165. */
  35166. set: function (value) {
  35167. if (this._exposure === value) {
  35168. return;
  35169. }
  35170. this._exposure = value;
  35171. this._updateParameters();
  35172. },
  35173. enumerable: true,
  35174. configurable: true
  35175. });
  35176. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  35177. /**
  35178. * Gets wether the tone mapping effect is enabled.
  35179. */
  35180. get: function () {
  35181. return this._toneMappingEnabled;
  35182. },
  35183. /**
  35184. * Sets wether the tone mapping effect is enabled.
  35185. */
  35186. set: function (value) {
  35187. if (this._toneMappingEnabled === value) {
  35188. return;
  35189. }
  35190. this._toneMappingEnabled = value;
  35191. this._updateParameters();
  35192. },
  35193. enumerable: true,
  35194. configurable: true
  35195. });
  35196. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  35197. /**
  35198. * Gets the contrast used in the effect.
  35199. */
  35200. get: function () {
  35201. return this._contrast;
  35202. },
  35203. /**
  35204. * Sets the contrast used in the effect.
  35205. */
  35206. set: function (value) {
  35207. if (this._contrast === value) {
  35208. return;
  35209. }
  35210. this._contrast = value;
  35211. this._updateParameters();
  35212. },
  35213. enumerable: true,
  35214. configurable: true
  35215. });
  35216. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  35217. /**
  35218. * Gets the vignette blend mode allowing different kind of effect.
  35219. */
  35220. get: function () {
  35221. return this._vignetteBlendMode;
  35222. },
  35223. /**
  35224. * Sets the vignette blend mode allowing different kind of effect.
  35225. */
  35226. set: function (value) {
  35227. if (this._vignetteBlendMode === value) {
  35228. return;
  35229. }
  35230. this._vignetteBlendMode = value;
  35231. this._updateParameters();
  35232. },
  35233. enumerable: true,
  35234. configurable: true
  35235. });
  35236. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  35237. /**
  35238. * Gets wether the vignette effect is enabled.
  35239. */
  35240. get: function () {
  35241. return this._vignetteEnabled;
  35242. },
  35243. /**
  35244. * Sets wether the vignette effect is enabled.
  35245. */
  35246. set: function (value) {
  35247. if (this._vignetteEnabled === value) {
  35248. return;
  35249. }
  35250. this._vignetteEnabled = value;
  35251. this._updateParameters();
  35252. },
  35253. enumerable: true,
  35254. configurable: true
  35255. });
  35256. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  35257. /**
  35258. * Gets wether the image processing is applied through a post process or not.
  35259. */
  35260. get: function () {
  35261. return this._applyByPostProcess;
  35262. },
  35263. /**
  35264. * Sets wether the image processing is applied through a post process or not.
  35265. */
  35266. set: function (value) {
  35267. if (this._applyByPostProcess === value) {
  35268. return;
  35269. }
  35270. this._applyByPostProcess = value;
  35271. this._updateParameters();
  35272. },
  35273. enumerable: true,
  35274. configurable: true
  35275. });
  35276. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  35277. /**
  35278. * Gets wether the image processing is enabled or not.
  35279. */
  35280. get: function () {
  35281. return this._isEnabled;
  35282. },
  35283. /**
  35284. * Sets wether the image processing is enabled or not.
  35285. */
  35286. set: function (value) {
  35287. if (this._isEnabled === value) {
  35288. return;
  35289. }
  35290. this._isEnabled = value;
  35291. this._updateParameters();
  35292. },
  35293. enumerable: true,
  35294. configurable: true
  35295. });
  35296. /**
  35297. * Method called each time the image processing information changes requires to recompile the effect.
  35298. */
  35299. ImageProcessingConfiguration.prototype._updateParameters = function () {
  35300. this.onUpdateParameters.notifyObservers(this);
  35301. };
  35302. ImageProcessingConfiguration.prototype.getClassName = function () {
  35303. return "ImageProcessingConfiguration";
  35304. };
  35305. /**
  35306. * Prepare the list of uniforms associated with the Image Processing effects.
  35307. * @param uniformsList The list of uniforms used in the effect
  35308. * @param defines the list of defines currently in use
  35309. */
  35310. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  35311. if (defines.EXPOSURE) {
  35312. uniforms.push("exposureLinear");
  35313. }
  35314. if (defines.CONTRAST) {
  35315. uniforms.push("contrast");
  35316. }
  35317. if (defines.COLORGRADING) {
  35318. uniforms.push("colorTransformSettings");
  35319. }
  35320. if (defines.VIGNETTE) {
  35321. uniforms.push("vInverseScreenSize");
  35322. uniforms.push("vignetteSettings1");
  35323. uniforms.push("vignetteSettings2");
  35324. }
  35325. if (defines.COLORCURVES) {
  35326. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35327. }
  35328. };
  35329. /**
  35330. * Prepare the list of samplers associated with the Image Processing effects.
  35331. * @param uniformsList The list of uniforms used in the effect
  35332. * @param defines the list of defines currently in use
  35333. */
  35334. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  35335. if (defines.COLORGRADING) {
  35336. samplersList.push("txColorTransform");
  35337. }
  35338. };
  35339. /**
  35340. * Prepare the list of defines associated to the shader.
  35341. * @param defines the list of defines to complete
  35342. */
  35343. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  35344. if (forPostProcess === void 0) { forPostProcess = false; }
  35345. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  35346. defines.VIGNETTE = false;
  35347. defines.TONEMAPPING = false;
  35348. defines.CONTRAST = false;
  35349. defines.EXPOSURE = false;
  35350. defines.COLORCURVES = false;
  35351. defines.COLORGRADING = false;
  35352. defines.COLORGRADING3D = false;
  35353. defines.IMAGEPROCESSING = false;
  35354. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  35355. return;
  35356. }
  35357. defines.VIGNETTE = this.vignetteEnabled;
  35358. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  35359. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  35360. defines.TONEMAPPING = this.toneMappingEnabled;
  35361. defines.CONTRAST = (this.contrast !== 1.0);
  35362. defines.EXPOSURE = (this.exposure !== 1.0);
  35363. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  35364. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  35365. if (defines.COLORGRADING) {
  35366. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  35367. }
  35368. else {
  35369. defines.COLORGRADING3D = false;
  35370. }
  35371. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  35372. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  35373. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  35374. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  35375. };
  35376. /**
  35377. * Returns true if all the image processing information are ready.
  35378. */
  35379. ImageProcessingConfiguration.prototype.isReady = function () {
  35380. // Color Grading texure can not be none blocking.
  35381. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  35382. };
  35383. /**
  35384. * Binds the image processing to the shader.
  35385. * @param effect The effect to bind to
  35386. */
  35387. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  35388. if (aspectRatio === void 0) { aspectRatio = 1; }
  35389. // Color Curves
  35390. if (this._colorCurvesEnabled && this.colorCurves) {
  35391. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  35392. }
  35393. // Vignette
  35394. if (this._vignetteEnabled) {
  35395. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  35396. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  35397. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  35398. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  35399. var vignetteScaleX = vignetteScaleY * aspectRatio;
  35400. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  35401. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  35402. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  35403. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  35404. var vignettePower = -2.0 * this.vignetteWeight;
  35405. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  35406. }
  35407. // Exposure
  35408. effect.setFloat("exposureLinear", this.exposure);
  35409. // Contrast
  35410. effect.setFloat("contrast", this.contrast);
  35411. // Color transform settings
  35412. if (this.colorGradingTexture) {
  35413. effect.setTexture("txColorTransform", this.colorGradingTexture);
  35414. var textureSize = this.colorGradingTexture.getSize().height;
  35415. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  35416. 0.5 / textureSize, // textureOffset
  35417. textureSize, // textureSize
  35418. this.colorGradingTexture.level // weight
  35419. );
  35420. }
  35421. };
  35422. /**
  35423. * Clones the current image processing instance.
  35424. * @return The cloned image processing
  35425. */
  35426. ImageProcessingConfiguration.prototype.clone = function () {
  35427. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  35428. };
  35429. /**
  35430. * Serializes the current image processing instance to a json representation.
  35431. * @return a JSON representation
  35432. */
  35433. ImageProcessingConfiguration.prototype.serialize = function () {
  35434. return BABYLON.SerializationHelper.Serialize(this);
  35435. };
  35436. /**
  35437. * Parses the image processing from a json representation.
  35438. * @param source the JSON source to parse
  35439. * @return The parsed image processing
  35440. */
  35441. ImageProcessingConfiguration.Parse = function (source) {
  35442. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  35443. };
  35444. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  35445. /**
  35446. * Used to apply the vignette as a mix with the pixel color.
  35447. */
  35448. get: function () {
  35449. return this._VIGNETTEMODE_MULTIPLY;
  35450. },
  35451. enumerable: true,
  35452. configurable: true
  35453. });
  35454. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  35455. /**
  35456. * Used to apply the vignette as a replacement of the pixel color.
  35457. */
  35458. get: function () {
  35459. return this._VIGNETTEMODE_OPAQUE;
  35460. },
  35461. enumerable: true,
  35462. configurable: true
  35463. });
  35464. // Static constants associated to the image processing.
  35465. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  35466. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  35467. __decorate([
  35468. BABYLON.serializeAsColorCurves()
  35469. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  35470. __decorate([
  35471. BABYLON.serialize()
  35472. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  35473. __decorate([
  35474. BABYLON.serializeAsTexture()
  35475. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  35476. __decorate([
  35477. BABYLON.serialize()
  35478. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  35479. __decorate([
  35480. BABYLON.serialize()
  35481. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  35482. __decorate([
  35483. BABYLON.serialize()
  35484. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  35485. __decorate([
  35486. BABYLON.serialize()
  35487. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  35488. __decorate([
  35489. BABYLON.serialize()
  35490. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  35491. __decorate([
  35492. BABYLON.serialize()
  35493. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  35494. __decorate([
  35495. BABYLON.serialize()
  35496. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  35497. __decorate([
  35498. BABYLON.serialize()
  35499. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  35500. __decorate([
  35501. BABYLON.serialize()
  35502. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  35503. __decorate([
  35504. BABYLON.serialize()
  35505. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  35506. __decorate([
  35507. BABYLON.serializeAsColor4()
  35508. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  35509. __decorate([
  35510. BABYLON.serialize()
  35511. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  35512. __decorate([
  35513. BABYLON.serialize()
  35514. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  35515. __decorate([
  35516. BABYLON.serialize()
  35517. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  35518. __decorate([
  35519. BABYLON.serialize()
  35520. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  35521. __decorate([
  35522. BABYLON.serialize()
  35523. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  35524. return ImageProcessingConfiguration;
  35525. }());
  35526. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  35527. })(BABYLON || (BABYLON = {}));
  35528. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  35529. var BABYLON;
  35530. (function (BABYLON) {
  35531. /**
  35532. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  35533. * It can help converting any input color in a desired output one. This can then be used to create effects
  35534. * from sepia, black and white to sixties or futuristic rendering...
  35535. *
  35536. * The only supported format is currently 3dl.
  35537. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  35538. */
  35539. var ColorGradingTexture = /** @class */ (function (_super) {
  35540. __extends(ColorGradingTexture, _super);
  35541. /**
  35542. * Instantiates a ColorGradingTexture from the following parameters.
  35543. *
  35544. * @param url The location of the color gradind data (currently only supporting 3dl)
  35545. * @param scene The scene the texture will be used in
  35546. */
  35547. function ColorGradingTexture(url, scene) {
  35548. var _this = _super.call(this, scene) || this;
  35549. if (!url) {
  35550. return _this;
  35551. }
  35552. _this._engine = scene.getEngine();
  35553. _this._textureMatrix = BABYLON.Matrix.Identity();
  35554. _this.name = url;
  35555. _this.url = url;
  35556. _this.hasAlpha = false;
  35557. _this.isCube = false;
  35558. _this.is3D = _this._engine.webGLVersion > 1;
  35559. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35560. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35561. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35562. _this.anisotropicFilteringLevel = 1;
  35563. _this._texture = _this._getFromCache(url, true);
  35564. if (!_this._texture) {
  35565. if (!scene.useDelayedTextureLoading) {
  35566. _this.loadTexture();
  35567. }
  35568. else {
  35569. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35570. }
  35571. }
  35572. return _this;
  35573. }
  35574. /**
  35575. * Returns the texture matrix used in most of the material.
  35576. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  35577. */
  35578. ColorGradingTexture.prototype.getTextureMatrix = function () {
  35579. return this._textureMatrix;
  35580. };
  35581. /**
  35582. * Occurs when the file being loaded is a .3dl LUT file.
  35583. */
  35584. ColorGradingTexture.prototype.load3dlTexture = function () {
  35585. var engine = this._engine;
  35586. var texture;
  35587. if (engine.webGLVersion === 1) {
  35588. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35589. }
  35590. else {
  35591. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35592. }
  35593. this._texture = texture;
  35594. var callback = function (text) {
  35595. if (typeof text !== "string") {
  35596. return;
  35597. }
  35598. var data = null;
  35599. var tempData = null;
  35600. var line;
  35601. var lines = text.split('\n');
  35602. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  35603. var maxColor = 0;
  35604. for (var i = 0; i < lines.length; i++) {
  35605. line = lines[i];
  35606. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  35607. continue;
  35608. if (line.indexOf('#') === 0)
  35609. continue;
  35610. var words = line.split(" ");
  35611. if (size === 0) {
  35612. // Number of space + one
  35613. size = words.length;
  35614. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  35615. tempData = new Float32Array(size * size * size * 4);
  35616. continue;
  35617. }
  35618. if (size != 0) {
  35619. var r = Math.max(parseInt(words[0]), 0);
  35620. var g = Math.max(parseInt(words[1]), 0);
  35621. var b = Math.max(parseInt(words[2]), 0);
  35622. maxColor = Math.max(r, maxColor);
  35623. maxColor = Math.max(g, maxColor);
  35624. maxColor = Math.max(b, maxColor);
  35625. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  35626. if (tempData) {
  35627. tempData[pixelStorageIndex + 0] = r;
  35628. tempData[pixelStorageIndex + 1] = g;
  35629. tempData[pixelStorageIndex + 2] = b;
  35630. }
  35631. pixelIndexSlice++;
  35632. if (pixelIndexSlice % size == 0) {
  35633. pixelIndexH++;
  35634. pixelIndexSlice = 0;
  35635. if (pixelIndexH % size == 0) {
  35636. pixelIndexW++;
  35637. pixelIndexH = 0;
  35638. }
  35639. }
  35640. }
  35641. }
  35642. if (tempData && data) {
  35643. for (var i = 0; i < tempData.length; i++) {
  35644. if (i > 0 && (i + 1) % 4 === 0) {
  35645. data[i] = 255;
  35646. }
  35647. else {
  35648. var value = tempData[i];
  35649. data[i] = (value / maxColor * 255);
  35650. }
  35651. }
  35652. }
  35653. if (texture.is3D) {
  35654. texture.updateSize(size, size, size);
  35655. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35656. }
  35657. else {
  35658. texture.updateSize(size * size, size);
  35659. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35660. }
  35661. };
  35662. var scene = this.getScene();
  35663. if (scene) {
  35664. scene._loadFile(this.url, callback);
  35665. }
  35666. else {
  35667. this._engine._loadFile(this.url, callback);
  35668. }
  35669. return this._texture;
  35670. };
  35671. /**
  35672. * Starts the loading process of the texture.
  35673. */
  35674. ColorGradingTexture.prototype.loadTexture = function () {
  35675. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  35676. this.load3dlTexture();
  35677. }
  35678. };
  35679. /**
  35680. * Clones the color gradind texture.
  35681. */
  35682. ColorGradingTexture.prototype.clone = function () {
  35683. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  35684. // Base texture
  35685. newTexture.level = this.level;
  35686. return newTexture;
  35687. };
  35688. /**
  35689. * Called during delayed load for textures.
  35690. */
  35691. ColorGradingTexture.prototype.delayLoad = function () {
  35692. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  35693. return;
  35694. }
  35695. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35696. this._texture = this._getFromCache(this.url, true);
  35697. if (!this._texture) {
  35698. this.loadTexture();
  35699. }
  35700. };
  35701. /**
  35702. * Parses a color grading texture serialized by Babylon.
  35703. * @param parsedTexture The texture information being parsedTexture
  35704. * @param scene The scene to load the texture in
  35705. * @param rootUrl The root url of the data assets to load
  35706. * @return A color gradind texture
  35707. */
  35708. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  35709. var texture = null;
  35710. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  35711. texture = new ColorGradingTexture(parsedTexture.name, scene);
  35712. texture.name = parsedTexture.name;
  35713. texture.level = parsedTexture.level;
  35714. }
  35715. return texture;
  35716. };
  35717. /**
  35718. * Serializes the LUT texture to json format.
  35719. */
  35720. ColorGradingTexture.prototype.serialize = function () {
  35721. if (!this.name) {
  35722. return null;
  35723. }
  35724. var serializationObject = {};
  35725. serializationObject.name = this.name;
  35726. serializationObject.level = this.level;
  35727. serializationObject.customType = "BABYLON.ColorGradingTexture";
  35728. return serializationObject;
  35729. };
  35730. /**
  35731. * Empty line regex stored for GC.
  35732. */
  35733. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  35734. return ColorGradingTexture;
  35735. }(BABYLON.BaseTexture));
  35736. BABYLON.ColorGradingTexture = ColorGradingTexture;
  35737. })(BABYLON || (BABYLON = {}));
  35738. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  35739. var BABYLON;
  35740. (function (BABYLON) {
  35741. /**
  35742. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35743. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35744. * 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;
  35745. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35746. */
  35747. var ColorCurves = /** @class */ (function () {
  35748. function ColorCurves() {
  35749. this._dirty = true;
  35750. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  35751. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  35752. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35753. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  35754. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35755. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  35756. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  35757. this._globalHue = 30;
  35758. this._globalDensity = 0;
  35759. this._globalSaturation = 0;
  35760. this._globalExposure = 0;
  35761. this._highlightsHue = 30;
  35762. this._highlightsDensity = 0;
  35763. this._highlightsSaturation = 0;
  35764. this._highlightsExposure = 0;
  35765. this._midtonesHue = 30;
  35766. this._midtonesDensity = 0;
  35767. this._midtonesSaturation = 0;
  35768. this._midtonesExposure = 0;
  35769. this._shadowsHue = 30;
  35770. this._shadowsDensity = 0;
  35771. this._shadowsSaturation = 0;
  35772. this._shadowsExposure = 0;
  35773. }
  35774. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  35775. /**
  35776. * Gets the global Hue value.
  35777. * 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).
  35778. */
  35779. get: function () {
  35780. return this._globalHue;
  35781. },
  35782. /**
  35783. * Sets the global Hue value.
  35784. * 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).
  35785. */
  35786. set: function (value) {
  35787. this._globalHue = value;
  35788. this._dirty = true;
  35789. },
  35790. enumerable: true,
  35791. configurable: true
  35792. });
  35793. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  35794. /**
  35795. * Gets the global Density value.
  35796. * 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.
  35797. * Values less than zero provide a filter of opposite hue.
  35798. */
  35799. get: function () {
  35800. return this._globalDensity;
  35801. },
  35802. /**
  35803. * Sets the global Density value.
  35804. * 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.
  35805. * Values less than zero provide a filter of opposite hue.
  35806. */
  35807. set: function (value) {
  35808. this._globalDensity = value;
  35809. this._dirty = true;
  35810. },
  35811. enumerable: true,
  35812. configurable: true
  35813. });
  35814. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35815. /**
  35816. * Gets the global Saturation value.
  35817. * 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.
  35818. */
  35819. get: function () {
  35820. return this._globalSaturation;
  35821. },
  35822. /**
  35823. * Sets the global Saturation value.
  35824. * 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.
  35825. */
  35826. set: function (value) {
  35827. this._globalSaturation = value;
  35828. this._dirty = true;
  35829. },
  35830. enumerable: true,
  35831. configurable: true
  35832. });
  35833. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35834. /**
  35835. * Gets the highlights Hue value.
  35836. * 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).
  35837. */
  35838. get: function () {
  35839. return this._highlightsHue;
  35840. },
  35841. /**
  35842. * Sets the highlights Hue value.
  35843. * 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).
  35844. */
  35845. set: function (value) {
  35846. this._highlightsHue = value;
  35847. this._dirty = true;
  35848. },
  35849. enumerable: true,
  35850. configurable: true
  35851. });
  35852. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35853. /**
  35854. * Gets the highlights Density value.
  35855. * 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.
  35856. * Values less than zero provide a filter of opposite hue.
  35857. */
  35858. get: function () {
  35859. return this._highlightsDensity;
  35860. },
  35861. /**
  35862. * Sets the highlights Density value.
  35863. * 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.
  35864. * Values less than zero provide a filter of opposite hue.
  35865. */
  35866. set: function (value) {
  35867. this._highlightsDensity = value;
  35868. this._dirty = true;
  35869. },
  35870. enumerable: true,
  35871. configurable: true
  35872. });
  35873. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35874. /**
  35875. * Gets the highlights Saturation value.
  35876. * 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.
  35877. */
  35878. get: function () {
  35879. return this._highlightsSaturation;
  35880. },
  35881. /**
  35882. * Sets the highlights Saturation value.
  35883. * 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.
  35884. */
  35885. set: function (value) {
  35886. this._highlightsSaturation = value;
  35887. this._dirty = true;
  35888. },
  35889. enumerable: true,
  35890. configurable: true
  35891. });
  35892. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35893. /**
  35894. * Gets the highlights Exposure value.
  35895. * 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.
  35896. */
  35897. get: function () {
  35898. return this._highlightsExposure;
  35899. },
  35900. /**
  35901. * Sets the highlights Exposure value.
  35902. * 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.
  35903. */
  35904. set: function (value) {
  35905. this._highlightsExposure = value;
  35906. this._dirty = true;
  35907. },
  35908. enumerable: true,
  35909. configurable: true
  35910. });
  35911. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35912. /**
  35913. * Gets the midtones Hue value.
  35914. * 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).
  35915. */
  35916. get: function () {
  35917. return this._midtonesHue;
  35918. },
  35919. /**
  35920. * Sets the midtones Hue value.
  35921. * 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).
  35922. */
  35923. set: function (value) {
  35924. this._midtonesHue = value;
  35925. this._dirty = true;
  35926. },
  35927. enumerable: true,
  35928. configurable: true
  35929. });
  35930. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35931. /**
  35932. * Gets the midtones Density value.
  35933. * 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.
  35934. * Values less than zero provide a filter of opposite hue.
  35935. */
  35936. get: function () {
  35937. return this._midtonesDensity;
  35938. },
  35939. /**
  35940. * Sets the midtones Density value.
  35941. * 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.
  35942. * Values less than zero provide a filter of opposite hue.
  35943. */
  35944. set: function (value) {
  35945. this._midtonesDensity = value;
  35946. this._dirty = true;
  35947. },
  35948. enumerable: true,
  35949. configurable: true
  35950. });
  35951. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35952. /**
  35953. * Gets the midtones Saturation value.
  35954. * 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.
  35955. */
  35956. get: function () {
  35957. return this._midtonesSaturation;
  35958. },
  35959. /**
  35960. * Sets the midtones Saturation value.
  35961. * 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.
  35962. */
  35963. set: function (value) {
  35964. this._midtonesSaturation = value;
  35965. this._dirty = true;
  35966. },
  35967. enumerable: true,
  35968. configurable: true
  35969. });
  35970. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35971. /**
  35972. * Gets the midtones Exposure value.
  35973. * 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.
  35974. */
  35975. get: function () {
  35976. return this._midtonesExposure;
  35977. },
  35978. /**
  35979. * Sets the midtones Exposure value.
  35980. * 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.
  35981. */
  35982. set: function (value) {
  35983. this._midtonesExposure = value;
  35984. this._dirty = true;
  35985. },
  35986. enumerable: true,
  35987. configurable: true
  35988. });
  35989. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  35990. /**
  35991. * Gets the shadows Hue value.
  35992. * 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).
  35993. */
  35994. get: function () {
  35995. return this._shadowsHue;
  35996. },
  35997. /**
  35998. * Sets the shadows Hue value.
  35999. * 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).
  36000. */
  36001. set: function (value) {
  36002. this._shadowsHue = value;
  36003. this._dirty = true;
  36004. },
  36005. enumerable: true,
  36006. configurable: true
  36007. });
  36008. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  36009. /**
  36010. * Gets the shadows Density value.
  36011. * 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.
  36012. * Values less than zero provide a filter of opposite hue.
  36013. */
  36014. get: function () {
  36015. return this._shadowsDensity;
  36016. },
  36017. /**
  36018. * Sets the shadows Density value.
  36019. * 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.
  36020. * Values less than zero provide a filter of opposite hue.
  36021. */
  36022. set: function (value) {
  36023. this._shadowsDensity = value;
  36024. this._dirty = true;
  36025. },
  36026. enumerable: true,
  36027. configurable: true
  36028. });
  36029. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  36030. /**
  36031. * Gets the shadows Saturation value.
  36032. * 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.
  36033. */
  36034. get: function () {
  36035. return this._shadowsSaturation;
  36036. },
  36037. /**
  36038. * Sets the shadows Saturation value.
  36039. * 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.
  36040. */
  36041. set: function (value) {
  36042. this._shadowsSaturation = value;
  36043. this._dirty = true;
  36044. },
  36045. enumerable: true,
  36046. configurable: true
  36047. });
  36048. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  36049. /**
  36050. * Gets the shadows Exposure value.
  36051. * 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.
  36052. */
  36053. get: function () {
  36054. return this._shadowsExposure;
  36055. },
  36056. /**
  36057. * Sets the shadows Exposure value.
  36058. * 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.
  36059. */
  36060. set: function (value) {
  36061. this._shadowsExposure = value;
  36062. this._dirty = true;
  36063. },
  36064. enumerable: true,
  36065. configurable: true
  36066. });
  36067. ColorCurves.prototype.getClassName = function () {
  36068. return "ColorCurves";
  36069. };
  36070. /**
  36071. * Binds the color curves to the shader.
  36072. * @param colorCurves The color curve to bind
  36073. * @param effect The effect to bind to
  36074. */
  36075. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  36076. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  36077. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  36078. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  36079. if (colorCurves._dirty) {
  36080. colorCurves._dirty = false;
  36081. // Fill in global info.
  36082. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  36083. // Compute highlights info.
  36084. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  36085. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  36086. // Compute midtones info.
  36087. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  36088. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  36089. // Compute shadows info.
  36090. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  36091. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  36092. // Compute deltas (neutral is midtones).
  36093. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  36094. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  36095. }
  36096. if (effect) {
  36097. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  36098. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  36099. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  36100. }
  36101. };
  36102. /**
  36103. * Prepare the list of uniforms associated with the ColorCurves effects.
  36104. * @param uniformsList The list of uniforms used in the effect
  36105. */
  36106. ColorCurves.PrepareUniforms = function (uniformsList) {
  36107. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  36108. };
  36109. /**
  36110. * Returns color grading data based on a hue, density, saturation and exposure value.
  36111. * @param filterHue The hue of the color filter.
  36112. * @param filterDensity The density of the color filter.
  36113. * @param saturation The saturation.
  36114. * @param exposure The exposure.
  36115. * @param result The result data container.
  36116. */
  36117. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  36118. if (hue == null) {
  36119. return;
  36120. }
  36121. hue = ColorCurves.clamp(hue, 0, 360);
  36122. density = ColorCurves.clamp(density, -100, 100);
  36123. saturation = ColorCurves.clamp(saturation, -100, 100);
  36124. exposure = ColorCurves.clamp(exposure, -100, 100);
  36125. // Remap the slider/config filter density with non-linear mapping and also scale by half
  36126. // so that the maximum filter density is only 50% control. This provides fine control
  36127. // for small values and reasonable range.
  36128. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  36129. density *= 0.5;
  36130. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  36131. if (density < 0) {
  36132. density *= -1;
  36133. hue = (hue + 180) % 360;
  36134. }
  36135. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  36136. result.scaleToRef(2, result);
  36137. result.a = 1 + 0.01 * saturation;
  36138. };
  36139. /**
  36140. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  36141. * @param value The input slider value in range [-100,100].
  36142. * @returns Adjusted value.
  36143. */
  36144. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  36145. value /= 100;
  36146. var x = Math.abs(value);
  36147. x = Math.pow(x, 2);
  36148. if (value < 0) {
  36149. x *= -1;
  36150. }
  36151. x *= 100;
  36152. return x;
  36153. };
  36154. /**
  36155. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  36156. * @param hue The hue (H) input.
  36157. * @param saturation The saturation (S) input.
  36158. * @param brightness The brightness (B) input.
  36159. * @result An RGBA color represented as Vector4.
  36160. */
  36161. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  36162. var h = ColorCurves.clamp(hue, 0, 360);
  36163. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  36164. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  36165. if (s === 0) {
  36166. result.r = v;
  36167. result.g = v;
  36168. result.b = v;
  36169. }
  36170. else {
  36171. // sector 0 to 5
  36172. h /= 60;
  36173. var i = Math.floor(h);
  36174. // fractional part of h
  36175. var f = h - i;
  36176. var p = v * (1 - s);
  36177. var q = v * (1 - s * f);
  36178. var t = v * (1 - s * (1 - f));
  36179. switch (i) {
  36180. case 0:
  36181. result.r = v;
  36182. result.g = t;
  36183. result.b = p;
  36184. break;
  36185. case 1:
  36186. result.r = q;
  36187. result.g = v;
  36188. result.b = p;
  36189. break;
  36190. case 2:
  36191. result.r = p;
  36192. result.g = v;
  36193. result.b = t;
  36194. break;
  36195. case 3:
  36196. result.r = p;
  36197. result.g = q;
  36198. result.b = v;
  36199. break;
  36200. case 4:
  36201. result.r = t;
  36202. result.g = p;
  36203. result.b = v;
  36204. break;
  36205. default:// case 5:
  36206. result.r = v;
  36207. result.g = p;
  36208. result.b = q;
  36209. break;
  36210. }
  36211. }
  36212. result.a = 1;
  36213. };
  36214. /**
  36215. * Returns a value clamped between min and max
  36216. * @param value The value to clamp
  36217. * @param min The minimum of value
  36218. * @param max The maximum of value
  36219. * @returns The clamped value.
  36220. */
  36221. ColorCurves.clamp = function (value, min, max) {
  36222. return Math.min(Math.max(value, min), max);
  36223. };
  36224. /**
  36225. * Clones the current color curve instance.
  36226. * @return The cloned curves
  36227. */
  36228. ColorCurves.prototype.clone = function () {
  36229. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  36230. };
  36231. /**
  36232. * Serializes the current color curve instance to a json representation.
  36233. * @return a JSON representation
  36234. */
  36235. ColorCurves.prototype.serialize = function () {
  36236. return BABYLON.SerializationHelper.Serialize(this);
  36237. };
  36238. /**
  36239. * Parses the color curve from a json representation.
  36240. * @param source the JSON source to parse
  36241. * @return The parsed curves
  36242. */
  36243. ColorCurves.Parse = function (source) {
  36244. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  36245. };
  36246. __decorate([
  36247. BABYLON.serialize()
  36248. ], ColorCurves.prototype, "_globalHue", void 0);
  36249. __decorate([
  36250. BABYLON.serialize()
  36251. ], ColorCurves.prototype, "_globalDensity", void 0);
  36252. __decorate([
  36253. BABYLON.serialize()
  36254. ], ColorCurves.prototype, "_globalSaturation", void 0);
  36255. __decorate([
  36256. BABYLON.serialize()
  36257. ], ColorCurves.prototype, "_globalExposure", void 0);
  36258. __decorate([
  36259. BABYLON.serialize()
  36260. ], ColorCurves.prototype, "_highlightsHue", void 0);
  36261. __decorate([
  36262. BABYLON.serialize()
  36263. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  36264. __decorate([
  36265. BABYLON.serialize()
  36266. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  36267. __decorate([
  36268. BABYLON.serialize()
  36269. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  36270. __decorate([
  36271. BABYLON.serialize()
  36272. ], ColorCurves.prototype, "_midtonesHue", void 0);
  36273. __decorate([
  36274. BABYLON.serialize()
  36275. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  36276. __decorate([
  36277. BABYLON.serialize()
  36278. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  36279. __decorate([
  36280. BABYLON.serialize()
  36281. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  36282. return ColorCurves;
  36283. }());
  36284. BABYLON.ColorCurves = ColorCurves;
  36285. })(BABYLON || (BABYLON = {}));
  36286. //# sourceMappingURL=babylon.colorCurves.js.map
  36287. //# sourceMappingURL=babylon.behavior.js.map
  36288. var BABYLON;
  36289. (function (BABYLON) {
  36290. /**
  36291. * "Static Class" containing the most commonly used helper while dealing with material for
  36292. * rendering purpose.
  36293. *
  36294. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  36295. *
  36296. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  36297. */
  36298. var MaterialHelper = /** @class */ (function () {
  36299. function MaterialHelper() {
  36300. }
  36301. /**
  36302. * Bind the current view position to an effect.
  36303. * @param effect The effect to be bound
  36304. * @param scene The scene the eyes position is used from
  36305. */
  36306. MaterialHelper.BindEyePosition = function (effect, scene) {
  36307. if (scene._forcedViewPosition) {
  36308. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  36309. return;
  36310. }
  36311. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36312. };
  36313. /**
  36314. * Helps preparing the defines values about the UVs in used in the effect.
  36315. * UVs are shared as much as we can accross chanels in the shaders.
  36316. * @param texture The texture we are preparing the UVs for
  36317. * @param defines The defines to update
  36318. * @param key The chanel key "diffuse", "specular"... used in the shader
  36319. */
  36320. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  36321. defines._needUVs = true;
  36322. defines[key] = true;
  36323. if (texture.getTextureMatrix().isIdentity(true)) {
  36324. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  36325. if (texture.coordinatesIndex === 0) {
  36326. defines["MAINUV1"] = true;
  36327. }
  36328. else {
  36329. defines["MAINUV2"] = true;
  36330. }
  36331. }
  36332. else {
  36333. defines[key + "DIRECTUV"] = 0;
  36334. }
  36335. };
  36336. /**
  36337. * Binds a texture matrix value to its corrsponding uniform
  36338. * @param texture The texture to bind the matrix for
  36339. * @param uniformBuffer The uniform buffer receivin the data
  36340. * @param key The chanel key "diffuse", "specular"... used in the shader
  36341. */
  36342. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  36343. var matrix = texture.getTextureMatrix();
  36344. if (!matrix.isIdentity(true)) {
  36345. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  36346. }
  36347. };
  36348. /**
  36349. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  36350. * @param mesh defines the current mesh
  36351. * @param scene defines the current scene
  36352. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  36353. * @param pointsCloud defines if point cloud rendering has to be turned on
  36354. * @param fogEnabled defines if fog has to be turned on
  36355. * @param alphaTest defines if alpha testing has to be turned on
  36356. * @param defines defines the current list of defines
  36357. */
  36358. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  36359. if (defines._areMiscDirty) {
  36360. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  36361. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  36362. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  36363. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  36364. defines["ALPHATEST"] = alphaTest;
  36365. }
  36366. };
  36367. /**
  36368. * Helper used to prepare the list of defines associated with frame values for shader compilation
  36369. * @param scene defines the current scene
  36370. * @param engine defines the current engine
  36371. * @param defines specifies the list of active defines
  36372. * @param useInstances defines if instances have to be turned on
  36373. */
  36374. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  36375. var changed = false;
  36376. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  36377. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  36378. changed = true;
  36379. }
  36380. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  36381. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  36382. changed = true;
  36383. }
  36384. if (defines["INSTANCES"] !== useInstances) {
  36385. defines["INSTANCES"] = useInstances;
  36386. changed = true;
  36387. }
  36388. if (changed) {
  36389. defines.markAsUnprocessed();
  36390. }
  36391. };
  36392. /**
  36393. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  36394. * @param mesh The mesh containing the geometry data we will draw
  36395. * @param defines The defines to update
  36396. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  36397. * @param useBones Precise whether bones should be used or not (override mesh info)
  36398. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  36399. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  36400. * @returns false if defines are considered not dirty and have not been checked
  36401. */
  36402. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  36403. if (useMorphTargets === void 0) { useMorphTargets = false; }
  36404. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  36405. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  36406. return false;
  36407. }
  36408. defines._normals = defines._needNormals;
  36409. defines._uvs = defines._needUVs;
  36410. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  36411. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36412. defines["TANGENT"] = true;
  36413. }
  36414. if (defines._needUVs) {
  36415. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  36416. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  36417. }
  36418. else {
  36419. defines["UV1"] = false;
  36420. defines["UV2"] = false;
  36421. }
  36422. if (useVertexColor) {
  36423. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  36424. defines["VERTEXCOLOR"] = hasVertexColors;
  36425. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  36426. }
  36427. if (useBones) {
  36428. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36429. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  36430. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  36431. }
  36432. else {
  36433. defines["NUM_BONE_INFLUENCERS"] = 0;
  36434. defines["BonesPerMesh"] = 0;
  36435. }
  36436. }
  36437. if (useMorphTargets) {
  36438. var manager = mesh.morphTargetManager;
  36439. if (manager) {
  36440. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  36441. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  36442. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  36443. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  36444. }
  36445. else {
  36446. defines["MORPHTARGETS_TANGENT"] = false;
  36447. defines["MORPHTARGETS_NORMAL"] = false;
  36448. defines["MORPHTARGETS"] = false;
  36449. defines["NUM_MORPH_INFLUENCERS"] = 0;
  36450. }
  36451. }
  36452. return true;
  36453. };
  36454. /**
  36455. * Prepares the defines related to the light information passed in parameter
  36456. * @param scene The scene we are intending to draw
  36457. * @param mesh The mesh the effect is compiling for
  36458. * @param defines The defines to update
  36459. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  36460. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  36461. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  36462. * @returns true if normals will be required for the rest of the effect
  36463. */
  36464. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  36465. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36466. if (disableLighting === void 0) { disableLighting = false; }
  36467. if (!defines._areLightsDirty) {
  36468. return defines._needNormals;
  36469. }
  36470. var lightIndex = 0;
  36471. var needNormals = false;
  36472. var needRebuild = false;
  36473. var lightmapMode = false;
  36474. var shadowEnabled = false;
  36475. var specularEnabled = false;
  36476. if (scene.lightsEnabled && !disableLighting) {
  36477. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  36478. var light = _a[_i];
  36479. needNormals = true;
  36480. if (defines["LIGHT" + lightIndex] === undefined) {
  36481. needRebuild = true;
  36482. }
  36483. defines["LIGHT" + lightIndex] = true;
  36484. defines["SPOTLIGHT" + lightIndex] = false;
  36485. defines["HEMILIGHT" + lightIndex] = false;
  36486. defines["POINTLIGHT" + lightIndex] = false;
  36487. defines["DIRLIGHT" + lightIndex] = false;
  36488. var type;
  36489. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  36490. type = "SPOTLIGHT" + lightIndex;
  36491. var spotLight = light;
  36492. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  36493. }
  36494. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  36495. type = "HEMILIGHT" + lightIndex;
  36496. }
  36497. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  36498. type = "POINTLIGHT" + lightIndex;
  36499. }
  36500. else {
  36501. type = "DIRLIGHT" + lightIndex;
  36502. }
  36503. defines[type] = true;
  36504. // Specular
  36505. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  36506. specularEnabled = true;
  36507. }
  36508. // Shadows
  36509. defines["SHADOW" + lightIndex] = false;
  36510. defines["SHADOWPCF" + lightIndex] = false;
  36511. defines["SHADOWESM" + lightIndex] = false;
  36512. defines["SHADOWCUBE" + lightIndex] = false;
  36513. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  36514. var shadowGenerator = light.getShadowGenerator();
  36515. if (shadowGenerator) {
  36516. shadowEnabled = true;
  36517. shadowGenerator.prepareDefines(defines, lightIndex);
  36518. }
  36519. }
  36520. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  36521. lightmapMode = true;
  36522. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  36523. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  36524. }
  36525. else {
  36526. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  36527. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  36528. }
  36529. lightIndex++;
  36530. if (lightIndex === maxSimultaneousLights)
  36531. break;
  36532. }
  36533. }
  36534. defines["SPECULARTERM"] = specularEnabled;
  36535. defines["SHADOWS"] = shadowEnabled;
  36536. // Resetting all other lights if any
  36537. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  36538. if (defines["LIGHT" + index] !== undefined) {
  36539. defines["LIGHT" + index] = false;
  36540. defines["HEMILIGHT" + lightIndex] = false;
  36541. defines["POINTLIGHT" + lightIndex] = false;
  36542. defines["DIRLIGHT" + lightIndex] = false;
  36543. defines["SPOTLIGHT" + lightIndex] = false;
  36544. defines["SHADOW" + lightIndex] = false;
  36545. }
  36546. }
  36547. var caps = scene.getEngine().getCaps();
  36548. if (defines["SHADOWFLOAT"] === undefined) {
  36549. needRebuild = true;
  36550. }
  36551. defines["SHADOWFLOAT"] = shadowEnabled &&
  36552. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  36553. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  36554. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  36555. if (needRebuild) {
  36556. defines.rebuild();
  36557. }
  36558. return needNormals;
  36559. };
  36560. /**
  36561. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  36562. * that won t be acctive due to defines being turned off.
  36563. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  36564. * @param samplersList The samplers list
  36565. * @param defines The defines helping in the list generation
  36566. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  36567. */
  36568. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  36569. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36570. var uniformsList;
  36571. var uniformBuffersList = null;
  36572. if (uniformsListOrOptions.uniformsNames) {
  36573. var options = uniformsListOrOptions;
  36574. uniformsList = options.uniformsNames;
  36575. uniformBuffersList = options.uniformBuffersNames;
  36576. samplersList = options.samplers;
  36577. defines = options.defines;
  36578. maxSimultaneousLights = options.maxSimultaneousLights;
  36579. }
  36580. else {
  36581. uniformsList = uniformsListOrOptions;
  36582. if (!samplersList) {
  36583. samplersList = [];
  36584. }
  36585. }
  36586. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36587. if (!defines["LIGHT" + lightIndex]) {
  36588. break;
  36589. }
  36590. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  36591. if (uniformBuffersList) {
  36592. uniformBuffersList.push("Light" + lightIndex);
  36593. }
  36594. samplersList.push("shadowSampler" + lightIndex);
  36595. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  36596. samplersList.push("projectionLightSampler" + lightIndex);
  36597. uniformsList.push("textureProjectionMatrix" + lightIndex);
  36598. }
  36599. }
  36600. if (defines["NUM_MORPH_INFLUENCERS"]) {
  36601. uniformsList.push("morphTargetInfluences");
  36602. }
  36603. };
  36604. /**
  36605. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  36606. * @param defines The defines to update while falling back
  36607. * @param fallbacks The authorized effect fallbacks
  36608. * @param maxSimultaneousLights The maximum number of lights allowed
  36609. * @param rank the current rank of the Effect
  36610. * @returns The newly affected rank
  36611. */
  36612. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  36613. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36614. if (rank === void 0) { rank = 0; }
  36615. var lightFallbackRank = 0;
  36616. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36617. if (!defines["LIGHT" + lightIndex]) {
  36618. break;
  36619. }
  36620. if (lightIndex > 0) {
  36621. lightFallbackRank = rank + lightIndex;
  36622. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  36623. }
  36624. if (!defines["SHADOWS"]) {
  36625. if (defines["SHADOW" + lightIndex]) {
  36626. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  36627. }
  36628. if (defines["SHADOWPCF" + lightIndex]) {
  36629. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  36630. }
  36631. if (defines["SHADOWESM" + lightIndex]) {
  36632. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  36633. }
  36634. }
  36635. }
  36636. return lightFallbackRank++;
  36637. };
  36638. /**
  36639. * Prepares the list of attributes required for morph targets according to the effect defines.
  36640. * @param attribs The current list of supported attribs
  36641. * @param mesh The mesh to prepare the morph targets attributes for
  36642. * @param defines The current Defines of the effect
  36643. */
  36644. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  36645. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  36646. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  36647. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  36648. var manager = mesh.morphTargetManager;
  36649. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  36650. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  36651. for (var index = 0; index < influencers; index++) {
  36652. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  36653. if (normal) {
  36654. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  36655. }
  36656. if (tangent) {
  36657. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  36658. }
  36659. if (attribs.length > maxAttributesCount) {
  36660. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  36661. }
  36662. }
  36663. }
  36664. };
  36665. /**
  36666. * Prepares the list of attributes required for bones according to the effect defines.
  36667. * @param attribs The current list of supported attribs
  36668. * @param mesh The mesh to prepare the bones attributes for
  36669. * @param defines The current Defines of the effect
  36670. * @param fallbacks The current efffect fallback strategy
  36671. */
  36672. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  36673. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  36674. fallbacks.addCPUSkinningFallback(0, mesh);
  36675. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36676. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36677. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  36678. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36679. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36680. }
  36681. }
  36682. };
  36683. /**
  36684. * Prepares the list of attributes required for instances according to the effect defines.
  36685. * @param attribs The current list of supported attribs
  36686. * @param defines The current Defines of the effect
  36687. */
  36688. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  36689. if (defines["INSTANCES"]) {
  36690. attribs.push("world0");
  36691. attribs.push("world1");
  36692. attribs.push("world2");
  36693. attribs.push("world3");
  36694. }
  36695. };
  36696. /**
  36697. * Binds the light shadow information to the effect for the given mesh.
  36698. * @param light The light containing the generator
  36699. * @param scene The scene the lights belongs to
  36700. * @param mesh The mesh we are binding the information to render
  36701. * @param lightIndex The light index in the effect used to render the mesh
  36702. * @param effect The effect we are binding the data to
  36703. */
  36704. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  36705. if (light.shadowEnabled && mesh.receiveShadows) {
  36706. var shadowGenerator = light.getShadowGenerator();
  36707. if (shadowGenerator) {
  36708. shadowGenerator.bindShadowLight(lightIndex, effect);
  36709. }
  36710. }
  36711. };
  36712. /**
  36713. * Binds the light information to the effect.
  36714. * @param light The light containing the generator
  36715. * @param effect The effect we are binding the data to
  36716. * @param lightIndex The light index in the effect used to render
  36717. */
  36718. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  36719. light.transferToEffect(effect, lightIndex + "");
  36720. };
  36721. /**
  36722. * Binds the lights information from the scene to the effect for the given mesh.
  36723. * @param scene The scene the lights belongs to
  36724. * @param mesh The mesh we are binding the information to render
  36725. * @param effect The effect we are binding the data to
  36726. * @param defines The generated defines for the effect
  36727. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  36728. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  36729. */
  36730. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  36731. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36732. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  36733. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  36734. for (var i = 0; i < len; i++) {
  36735. var light = mesh._lightSources[i];
  36736. var iAsString = i.toString();
  36737. var scaledIntensity = light.getScaledIntensity();
  36738. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  36739. MaterialHelper.BindLightProperties(light, effect, i);
  36740. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  36741. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  36742. if (defines["SPECULARTERM"]) {
  36743. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  36744. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  36745. }
  36746. // Shadows
  36747. if (scene.shadowsEnabled) {
  36748. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  36749. }
  36750. light._uniformBuffer.update();
  36751. }
  36752. };
  36753. /**
  36754. * Binds the fog information from the scene to the effect for the given mesh.
  36755. * @param scene The scene the lights belongs to
  36756. * @param mesh The mesh we are binding the information to render
  36757. * @param effect The effect we are binding the data to
  36758. */
  36759. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  36760. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  36761. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  36762. effect.setColor3("vFogColor", scene.fogColor);
  36763. }
  36764. };
  36765. /**
  36766. * Binds the bones information from the mesh to the effect.
  36767. * @param mesh The mesh we are binding the information to render
  36768. * @param effect The effect we are binding the data to
  36769. */
  36770. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  36771. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36772. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  36773. if (matrices && effect) {
  36774. effect.setMatrices("mBones", matrices);
  36775. }
  36776. }
  36777. };
  36778. /**
  36779. * Binds the morph targets information from the mesh to the effect.
  36780. * @param abstractMesh The mesh we are binding the information to render
  36781. * @param effect The effect we are binding the data to
  36782. */
  36783. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  36784. var manager = abstractMesh.morphTargetManager;
  36785. if (!abstractMesh || !manager) {
  36786. return;
  36787. }
  36788. effect.setFloatArray("morphTargetInfluences", manager.influences);
  36789. };
  36790. /**
  36791. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  36792. * @param defines The generated defines used in the effect
  36793. * @param effect The effect we are binding the data to
  36794. * @param scene The scene we are willing to render with logarithmic scale for
  36795. */
  36796. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  36797. if (defines["LOGARITHMICDEPTH"]) {
  36798. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  36799. }
  36800. };
  36801. /**
  36802. * Binds the clip plane information from the scene to the effect.
  36803. * @param scene The scene the clip plane information are extracted from
  36804. * @param effect The effect we are binding the data to
  36805. */
  36806. MaterialHelper.BindClipPlane = function (effect, scene) {
  36807. if (scene.clipPlane) {
  36808. var clipPlane = scene.clipPlane;
  36809. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36810. }
  36811. };
  36812. return MaterialHelper;
  36813. }());
  36814. BABYLON.MaterialHelper = MaterialHelper;
  36815. })(BABYLON || (BABYLON = {}));
  36816. //# sourceMappingURL=babylon.materialHelper.js.map
  36817. var BABYLON;
  36818. (function (BABYLON) {
  36819. var PushMaterial = /** @class */ (function (_super) {
  36820. __extends(PushMaterial, _super);
  36821. function PushMaterial(name, scene) {
  36822. var _this = _super.call(this, name, scene) || this;
  36823. _this.storeEffectOnSubMeshes = true;
  36824. return _this;
  36825. }
  36826. PushMaterial.prototype.getEffect = function () {
  36827. return this._activeEffect;
  36828. };
  36829. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  36830. if (!mesh) {
  36831. return false;
  36832. }
  36833. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  36834. return true;
  36835. }
  36836. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  36837. };
  36838. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36839. this._activeEffect.setMatrix("world", world);
  36840. };
  36841. PushMaterial.prototype.bind = function (world, mesh) {
  36842. if (!mesh) {
  36843. return;
  36844. }
  36845. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  36846. };
  36847. PushMaterial.prototype._afterBind = function (mesh, effect) {
  36848. if (effect === void 0) { effect = null; }
  36849. _super.prototype._afterBind.call(this, mesh);
  36850. this.getScene()._cachedEffect = effect;
  36851. };
  36852. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  36853. if (visibility === void 0) { visibility = 1; }
  36854. return scene.isCachedMaterialInvalid(this, effect, visibility);
  36855. };
  36856. return PushMaterial;
  36857. }(BABYLON.Material));
  36858. BABYLON.PushMaterial = PushMaterial;
  36859. })(BABYLON || (BABYLON = {}));
  36860. //# sourceMappingURL=babylon.pushMaterial.js.map
  36861. var BABYLON;
  36862. (function (BABYLON) {
  36863. var StandardMaterialDefines = /** @class */ (function (_super) {
  36864. __extends(StandardMaterialDefines, _super);
  36865. function StandardMaterialDefines() {
  36866. var _this = _super.call(this) || this;
  36867. _this.MAINUV1 = false;
  36868. _this.MAINUV2 = false;
  36869. _this.DIFFUSE = false;
  36870. _this.DIFFUSEDIRECTUV = 0;
  36871. _this.AMBIENT = false;
  36872. _this.AMBIENTDIRECTUV = 0;
  36873. _this.OPACITY = false;
  36874. _this.OPACITYDIRECTUV = 0;
  36875. _this.OPACITYRGB = false;
  36876. _this.REFLECTION = false;
  36877. _this.EMISSIVE = false;
  36878. _this.EMISSIVEDIRECTUV = 0;
  36879. _this.SPECULAR = false;
  36880. _this.SPECULARDIRECTUV = 0;
  36881. _this.BUMP = false;
  36882. _this.BUMPDIRECTUV = 0;
  36883. _this.PARALLAX = false;
  36884. _this.PARALLAXOCCLUSION = false;
  36885. _this.SPECULAROVERALPHA = false;
  36886. _this.CLIPPLANE = false;
  36887. _this.ALPHATEST = false;
  36888. _this.DEPTHPREPASS = false;
  36889. _this.ALPHAFROMDIFFUSE = false;
  36890. _this.POINTSIZE = false;
  36891. _this.FOG = false;
  36892. _this.SPECULARTERM = false;
  36893. _this.DIFFUSEFRESNEL = false;
  36894. _this.OPACITYFRESNEL = false;
  36895. _this.REFLECTIONFRESNEL = false;
  36896. _this.REFRACTIONFRESNEL = false;
  36897. _this.EMISSIVEFRESNEL = false;
  36898. _this.FRESNEL = false;
  36899. _this.NORMAL = false;
  36900. _this.UV1 = false;
  36901. _this.UV2 = false;
  36902. _this.VERTEXCOLOR = false;
  36903. _this.VERTEXALPHA = false;
  36904. _this.NUM_BONE_INFLUENCERS = 0;
  36905. _this.BonesPerMesh = 0;
  36906. _this.INSTANCES = false;
  36907. _this.GLOSSINESS = false;
  36908. _this.ROUGHNESS = false;
  36909. _this.EMISSIVEASILLUMINATION = false;
  36910. _this.LINKEMISSIVEWITHDIFFUSE = false;
  36911. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  36912. _this.LIGHTMAP = false;
  36913. _this.LIGHTMAPDIRECTUV = 0;
  36914. _this.USELIGHTMAPASSHADOWMAP = false;
  36915. _this.REFLECTIONMAP_3D = false;
  36916. _this.REFLECTIONMAP_SPHERICAL = false;
  36917. _this.REFLECTIONMAP_PLANAR = false;
  36918. _this.REFLECTIONMAP_CUBIC = false;
  36919. _this.REFLECTIONMAP_PROJECTION = false;
  36920. _this.REFLECTIONMAP_SKYBOX = false;
  36921. _this.REFLECTIONMAP_EXPLICIT = false;
  36922. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36923. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36924. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36925. _this.INVERTCUBICMAP = false;
  36926. _this.LOGARITHMICDEPTH = false;
  36927. _this.REFRACTION = false;
  36928. _this.REFRACTIONMAP_3D = false;
  36929. _this.REFLECTIONOVERALPHA = false;
  36930. _this.TWOSIDEDLIGHTING = false;
  36931. _this.SHADOWFLOAT = false;
  36932. _this.MORPHTARGETS = false;
  36933. _this.MORPHTARGETS_NORMAL = false;
  36934. _this.MORPHTARGETS_TANGENT = false;
  36935. _this.NUM_MORPH_INFLUENCERS = 0;
  36936. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  36937. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  36938. _this.IMAGEPROCESSING = false;
  36939. _this.VIGNETTE = false;
  36940. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36941. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36942. _this.TONEMAPPING = false;
  36943. _this.CONTRAST = false;
  36944. _this.COLORCURVES = false;
  36945. _this.COLORGRADING = false;
  36946. _this.COLORGRADING3D = false;
  36947. _this.SAMPLER3DGREENDEPTH = false;
  36948. _this.SAMPLER3DBGRMAP = false;
  36949. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36950. _this.EXPOSURE = false;
  36951. _this.rebuild();
  36952. return _this;
  36953. }
  36954. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  36955. var modes = [
  36956. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36957. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36958. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36959. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36960. ];
  36961. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36962. var mode = modes_1[_i];
  36963. this[mode] = (mode === modeToEnable);
  36964. }
  36965. };
  36966. return StandardMaterialDefines;
  36967. }(BABYLON.MaterialDefines));
  36968. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36969. var StandardMaterial = /** @class */ (function (_super) {
  36970. __extends(StandardMaterial, _super);
  36971. function StandardMaterial(name, scene) {
  36972. var _this = _super.call(this, name, scene) || this;
  36973. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36974. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36975. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36976. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36977. _this.specularPower = 64;
  36978. _this._useAlphaFromDiffuseTexture = false;
  36979. _this._useEmissiveAsIllumination = false;
  36980. _this._linkEmissiveWithDiffuse = false;
  36981. _this._useSpecularOverAlpha = false;
  36982. _this._useReflectionOverAlpha = false;
  36983. _this._disableLighting = false;
  36984. _this._useParallax = false;
  36985. _this._useParallaxOcclusion = false;
  36986. _this.parallaxScaleBias = 0.05;
  36987. _this._roughness = 0;
  36988. _this.indexOfRefraction = 0.98;
  36989. _this.invertRefractionY = true;
  36990. _this._useLightmapAsShadowmap = false;
  36991. _this._useReflectionFresnelFromSpecular = false;
  36992. _this._useGlossinessFromSpecularMapAlpha = false;
  36993. _this._maxSimultaneousLights = 4;
  36994. /**
  36995. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36996. */
  36997. _this._invertNormalMapX = false;
  36998. /**
  36999. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37000. */
  37001. _this._invertNormalMapY = false;
  37002. /**
  37003. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37004. */
  37005. _this._twoSidedLighting = false;
  37006. _this._renderTargets = new BABYLON.SmartArray(16);
  37007. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  37008. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37009. // Setup the default processing configuration to the scene.
  37010. _this._attachImageProcessingConfiguration(null);
  37011. _this.getRenderTargetTextures = function () {
  37012. _this._renderTargets.reset();
  37013. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37014. _this._renderTargets.push(_this._reflectionTexture);
  37015. }
  37016. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37017. _this._renderTargets.push(_this._refractionTexture);
  37018. }
  37019. return _this._renderTargets;
  37020. };
  37021. return _this;
  37022. }
  37023. ;
  37024. ;
  37025. ;
  37026. ;
  37027. ;
  37028. ;
  37029. ;
  37030. ;
  37031. ;
  37032. ;
  37033. ;
  37034. ;
  37035. ;
  37036. ;
  37037. ;
  37038. ;
  37039. ;
  37040. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  37041. /**
  37042. * Gets the image processing configuration used either in this material.
  37043. */
  37044. get: function () {
  37045. return this._imageProcessingConfiguration;
  37046. },
  37047. /**
  37048. * Sets the Default image processing configuration used either in the this material.
  37049. *
  37050. * If sets to null, the scene one is in use.
  37051. */
  37052. set: function (value) {
  37053. this._attachImageProcessingConfiguration(value);
  37054. // Ensure the effect will be rebuilt.
  37055. this._markAllSubMeshesAsTexturesDirty();
  37056. },
  37057. enumerable: true,
  37058. configurable: true
  37059. });
  37060. /**
  37061. * Attaches a new image processing configuration to the Standard Material.
  37062. * @param configuration
  37063. */
  37064. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37065. var _this = this;
  37066. if (configuration === this._imageProcessingConfiguration) {
  37067. return;
  37068. }
  37069. // Detaches observer.
  37070. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37071. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37072. }
  37073. // Pick the scene configuration if needed.
  37074. if (!configuration) {
  37075. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37076. }
  37077. else {
  37078. this._imageProcessingConfiguration = configuration;
  37079. }
  37080. // Attaches observer.
  37081. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37082. _this._markAllSubMeshesAsImageProcessingDirty();
  37083. });
  37084. };
  37085. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  37086. /**
  37087. * Gets wether the color curves effect is enabled.
  37088. */
  37089. get: function () {
  37090. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37091. },
  37092. /**
  37093. * Sets wether the color curves effect is enabled.
  37094. */
  37095. set: function (value) {
  37096. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37097. },
  37098. enumerable: true,
  37099. configurable: true
  37100. });
  37101. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  37102. /**
  37103. * Gets wether the color grading effect is enabled.
  37104. */
  37105. get: function () {
  37106. return this.imageProcessingConfiguration.colorGradingEnabled;
  37107. },
  37108. /**
  37109. * Gets wether the color grading effect is enabled.
  37110. */
  37111. set: function (value) {
  37112. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37113. },
  37114. enumerable: true,
  37115. configurable: true
  37116. });
  37117. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  37118. /**
  37119. * Gets wether tonemapping is enabled or not.
  37120. */
  37121. get: function () {
  37122. return this._imageProcessingConfiguration.toneMappingEnabled;
  37123. },
  37124. /**
  37125. * Sets wether tonemapping is enabled or not
  37126. */
  37127. set: function (value) {
  37128. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37129. },
  37130. enumerable: true,
  37131. configurable: true
  37132. });
  37133. ;
  37134. ;
  37135. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  37136. /**
  37137. * The camera exposure used on this material.
  37138. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37139. * This corresponds to a photographic exposure.
  37140. */
  37141. get: function () {
  37142. return this._imageProcessingConfiguration.exposure;
  37143. },
  37144. /**
  37145. * The camera exposure used on this material.
  37146. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37147. * This corresponds to a photographic exposure.
  37148. */
  37149. set: function (value) {
  37150. this._imageProcessingConfiguration.exposure = value;
  37151. },
  37152. enumerable: true,
  37153. configurable: true
  37154. });
  37155. ;
  37156. ;
  37157. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  37158. /**
  37159. * Gets The camera contrast used on this material.
  37160. */
  37161. get: function () {
  37162. return this._imageProcessingConfiguration.contrast;
  37163. },
  37164. /**
  37165. * Sets The camera contrast used on this material.
  37166. */
  37167. set: function (value) {
  37168. this._imageProcessingConfiguration.contrast = value;
  37169. },
  37170. enumerable: true,
  37171. configurable: true
  37172. });
  37173. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  37174. /**
  37175. * Gets the Color Grading 2D Lookup Texture.
  37176. */
  37177. get: function () {
  37178. return this._imageProcessingConfiguration.colorGradingTexture;
  37179. },
  37180. /**
  37181. * Sets the Color Grading 2D Lookup Texture.
  37182. */
  37183. set: function (value) {
  37184. this._imageProcessingConfiguration.colorGradingTexture = value;
  37185. },
  37186. enumerable: true,
  37187. configurable: true
  37188. });
  37189. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  37190. /**
  37191. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37192. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37193. * 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;
  37194. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37195. */
  37196. get: function () {
  37197. return this._imageProcessingConfiguration.colorCurves;
  37198. },
  37199. /**
  37200. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37201. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37202. * 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;
  37203. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37204. */
  37205. set: function (value) {
  37206. this._imageProcessingConfiguration.colorCurves = value;
  37207. },
  37208. enumerable: true,
  37209. configurable: true
  37210. });
  37211. StandardMaterial.prototype.getClassName = function () {
  37212. return "StandardMaterial";
  37213. };
  37214. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  37215. get: function () {
  37216. return this._useLogarithmicDepth;
  37217. },
  37218. set: function (value) {
  37219. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37220. this._markAllSubMeshesAsMiscDirty();
  37221. },
  37222. enumerable: true,
  37223. configurable: true
  37224. });
  37225. StandardMaterial.prototype.needAlphaBlending = function () {
  37226. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  37227. };
  37228. StandardMaterial.prototype.needAlphaTesting = function () {
  37229. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  37230. };
  37231. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  37232. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  37233. };
  37234. StandardMaterial.prototype.getAlphaTestTexture = function () {
  37235. return this._diffuseTexture;
  37236. };
  37237. /**
  37238. * Child classes can use it to update shaders
  37239. */
  37240. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37241. if (useInstances === void 0) { useInstances = false; }
  37242. if (subMesh.effect && this.isFrozen) {
  37243. if (this._wasPreviouslyReady && subMesh.effect) {
  37244. return true;
  37245. }
  37246. }
  37247. if (!subMesh._materialDefines) {
  37248. subMesh._materialDefines = new StandardMaterialDefines();
  37249. }
  37250. var scene = this.getScene();
  37251. var defines = subMesh._materialDefines;
  37252. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37253. if (defines._renderId === scene.getRenderId()) {
  37254. return true;
  37255. }
  37256. }
  37257. var engine = scene.getEngine();
  37258. // Lights
  37259. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37260. // Textures
  37261. if (defines._areTexturesDirty) {
  37262. defines._needUVs = false;
  37263. defines.MAINUV1 = false;
  37264. defines.MAINUV2 = false;
  37265. if (scene.texturesEnabled) {
  37266. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37267. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  37268. return false;
  37269. }
  37270. else {
  37271. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  37272. }
  37273. }
  37274. else {
  37275. defines.DIFFUSE = false;
  37276. }
  37277. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37278. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37279. return false;
  37280. }
  37281. else {
  37282. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37283. }
  37284. }
  37285. else {
  37286. defines.AMBIENT = false;
  37287. }
  37288. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37289. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37290. return false;
  37291. }
  37292. else {
  37293. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37294. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37295. }
  37296. }
  37297. else {
  37298. defines.OPACITY = false;
  37299. }
  37300. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37301. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  37302. return false;
  37303. }
  37304. else {
  37305. defines._needNormals = true;
  37306. defines.REFLECTION = true;
  37307. defines.ROUGHNESS = (this._roughness > 0);
  37308. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  37309. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  37310. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  37311. switch (this._reflectionTexture.coordinatesMode) {
  37312. case BABYLON.Texture.CUBIC_MODE:
  37313. case BABYLON.Texture.INVCUBIC_MODE:
  37314. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  37315. break;
  37316. case BABYLON.Texture.EXPLICIT_MODE:
  37317. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  37318. break;
  37319. case BABYLON.Texture.PLANAR_MODE:
  37320. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  37321. break;
  37322. case BABYLON.Texture.PROJECTION_MODE:
  37323. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  37324. break;
  37325. case BABYLON.Texture.SKYBOX_MODE:
  37326. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  37327. break;
  37328. case BABYLON.Texture.SPHERICAL_MODE:
  37329. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  37330. break;
  37331. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37332. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  37333. break;
  37334. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37335. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  37336. break;
  37337. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37338. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  37339. break;
  37340. }
  37341. }
  37342. }
  37343. else {
  37344. defines.REFLECTION = false;
  37345. }
  37346. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37347. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37348. return false;
  37349. }
  37350. else {
  37351. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37352. }
  37353. }
  37354. else {
  37355. defines.EMISSIVE = false;
  37356. }
  37357. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37358. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37359. return false;
  37360. }
  37361. else {
  37362. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37363. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37364. }
  37365. }
  37366. else {
  37367. defines.LIGHTMAP = false;
  37368. }
  37369. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37370. if (!this._specularTexture.isReadyOrNotBlocking()) {
  37371. return false;
  37372. }
  37373. else {
  37374. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  37375. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  37376. }
  37377. }
  37378. else {
  37379. defines.SPECULAR = false;
  37380. }
  37381. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  37382. // Bump texure can not be not blocking.
  37383. if (!this._bumpTexture.isReady()) {
  37384. return false;
  37385. }
  37386. else {
  37387. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37388. defines.PARALLAX = this._useParallax;
  37389. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  37390. }
  37391. }
  37392. else {
  37393. defines.BUMP = false;
  37394. }
  37395. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37396. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  37397. return false;
  37398. }
  37399. else {
  37400. defines._needUVs = true;
  37401. defines.REFRACTION = true;
  37402. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  37403. }
  37404. }
  37405. else {
  37406. defines.REFRACTION = false;
  37407. }
  37408. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  37409. }
  37410. else {
  37411. defines.DIFFUSE = false;
  37412. defines.AMBIENT = false;
  37413. defines.OPACITY = false;
  37414. defines.REFLECTION = false;
  37415. defines.EMISSIVE = false;
  37416. defines.LIGHTMAP = false;
  37417. defines.BUMP = false;
  37418. defines.REFRACTION = false;
  37419. }
  37420. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  37421. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  37422. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  37423. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37424. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37425. }
  37426. if (defines._areImageProcessingDirty) {
  37427. if (!this._imageProcessingConfiguration.isReady()) {
  37428. return false;
  37429. }
  37430. this._imageProcessingConfiguration.prepareDefines(defines);
  37431. }
  37432. if (defines._areFresnelDirty) {
  37433. if (StandardMaterial.FresnelEnabled) {
  37434. // Fresnel
  37435. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  37436. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  37437. this._reflectionFresnelParameters) {
  37438. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  37439. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  37440. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  37441. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  37442. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  37443. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  37444. defines._needNormals = true;
  37445. defines.FRESNEL = true;
  37446. }
  37447. }
  37448. else {
  37449. defines.FRESNEL = false;
  37450. }
  37451. }
  37452. // Misc.
  37453. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  37454. // Attribs
  37455. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  37456. // Values that need to be evaluated on every frame
  37457. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  37458. // Get correct effect
  37459. if (defines.isDirty) {
  37460. defines.markAsProcessed();
  37461. scene.resetCachedMaterial();
  37462. // Fallbacks
  37463. var fallbacks = new BABYLON.EffectFallbacks();
  37464. if (defines.REFLECTION) {
  37465. fallbacks.addFallback(0, "REFLECTION");
  37466. }
  37467. if (defines.SPECULAR) {
  37468. fallbacks.addFallback(0, "SPECULAR");
  37469. }
  37470. if (defines.BUMP) {
  37471. fallbacks.addFallback(0, "BUMP");
  37472. }
  37473. if (defines.PARALLAX) {
  37474. fallbacks.addFallback(1, "PARALLAX");
  37475. }
  37476. if (defines.PARALLAXOCCLUSION) {
  37477. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37478. }
  37479. if (defines.SPECULAROVERALPHA) {
  37480. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37481. }
  37482. if (defines.FOG) {
  37483. fallbacks.addFallback(1, "FOG");
  37484. }
  37485. if (defines.POINTSIZE) {
  37486. fallbacks.addFallback(0, "POINTSIZE");
  37487. }
  37488. if (defines.LOGARITHMICDEPTH) {
  37489. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37490. }
  37491. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37492. if (defines.SPECULARTERM) {
  37493. fallbacks.addFallback(0, "SPECULARTERM");
  37494. }
  37495. if (defines.DIFFUSEFRESNEL) {
  37496. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  37497. }
  37498. if (defines.OPACITYFRESNEL) {
  37499. fallbacks.addFallback(2, "OPACITYFRESNEL");
  37500. }
  37501. if (defines.REFLECTIONFRESNEL) {
  37502. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  37503. }
  37504. if (defines.EMISSIVEFRESNEL) {
  37505. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  37506. }
  37507. if (defines.FRESNEL) {
  37508. fallbacks.addFallback(4, "FRESNEL");
  37509. }
  37510. //Attributes
  37511. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37512. if (defines.NORMAL) {
  37513. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37514. }
  37515. if (defines.UV1) {
  37516. attribs.push(BABYLON.VertexBuffer.UVKind);
  37517. }
  37518. if (defines.UV2) {
  37519. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37520. }
  37521. if (defines.VERTEXCOLOR) {
  37522. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37523. }
  37524. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37525. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37526. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37527. var shaderName = "default";
  37528. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  37529. "vFogInfos", "vFogColor", "pointSize",
  37530. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37531. "mBones",
  37532. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37533. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  37534. "logarithmicDepthConstant", "vTangentSpaceParams"
  37535. ];
  37536. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  37537. var uniformBuffers = ["Material", "Scene"];
  37538. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37539. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37540. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37541. uniformsNames: uniforms,
  37542. uniformBuffersNames: uniformBuffers,
  37543. samplers: samplers,
  37544. defines: defines,
  37545. maxSimultaneousLights: this._maxSimultaneousLights
  37546. });
  37547. if (this.customShaderNameResolve) {
  37548. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  37549. }
  37550. var join = defines.toString();
  37551. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  37552. attributes: attribs,
  37553. uniformsNames: uniforms,
  37554. uniformBuffersNames: uniformBuffers,
  37555. samplers: samplers,
  37556. defines: join,
  37557. fallbacks: fallbacks,
  37558. onCompiled: this.onCompiled,
  37559. onError: this.onError,
  37560. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37561. }, engine), defines);
  37562. this.buildUniformLayout();
  37563. }
  37564. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37565. return false;
  37566. }
  37567. defines._renderId = scene.getRenderId();
  37568. this._wasPreviouslyReady = true;
  37569. return true;
  37570. };
  37571. StandardMaterial.prototype.buildUniformLayout = function () {
  37572. // Order is important !
  37573. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  37574. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  37575. this._uniformBuffer.addUniform("opacityParts", 4);
  37576. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  37577. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  37578. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  37579. this._uniformBuffer.addUniform("refractionRightColor", 4);
  37580. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  37581. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  37582. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  37583. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  37584. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37585. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37586. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37587. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37588. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  37589. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37590. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  37591. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37592. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37593. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37594. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37595. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37596. this._uniformBuffer.addUniform("specularMatrix", 16);
  37597. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37598. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37599. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37600. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37601. this._uniformBuffer.addUniform("vSpecularColor", 4);
  37602. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37603. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  37604. this._uniformBuffer.addUniform("pointSize", 1);
  37605. this._uniformBuffer.create();
  37606. };
  37607. StandardMaterial.prototype.unbind = function () {
  37608. if (this._activeEffect) {
  37609. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37610. this._activeEffect.setTexture("reflection2DSampler", null);
  37611. }
  37612. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37613. this._activeEffect.setTexture("refraction2DSampler", null);
  37614. }
  37615. }
  37616. _super.prototype.unbind.call(this);
  37617. };
  37618. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37619. var scene = this.getScene();
  37620. var defines = subMesh._materialDefines;
  37621. if (!defines) {
  37622. return;
  37623. }
  37624. var effect = subMesh.effect;
  37625. if (!effect) {
  37626. return;
  37627. }
  37628. this._activeEffect = effect;
  37629. // Matrices
  37630. this.bindOnlyWorldMatrix(world);
  37631. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37632. // Bones
  37633. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  37634. if (mustRebind) {
  37635. this._uniformBuffer.bindToEffect(effect, "Material");
  37636. this.bindViewProjection(effect);
  37637. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37638. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  37639. // Fresnel
  37640. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  37641. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  37642. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  37643. }
  37644. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  37645. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  37646. }
  37647. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  37648. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  37649. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  37650. }
  37651. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  37652. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  37653. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  37654. }
  37655. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  37656. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  37657. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  37658. }
  37659. }
  37660. // Textures
  37661. if (scene.texturesEnabled) {
  37662. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37663. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  37664. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  37665. }
  37666. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37667. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  37668. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37669. }
  37670. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37671. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37672. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37673. }
  37674. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37675. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  37676. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  37677. }
  37678. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37679. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37680. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37681. }
  37682. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37683. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37684. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37685. }
  37686. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37687. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  37688. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  37689. }
  37690. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37691. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  37692. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37693. if (scene._mirroredCameraPosition) {
  37694. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37695. }
  37696. else {
  37697. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37698. }
  37699. }
  37700. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37701. var depth = 1.0;
  37702. if (!this._refractionTexture.isCube) {
  37703. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  37704. if (this._refractionTexture.depth) {
  37705. depth = this._refractionTexture.depth;
  37706. }
  37707. }
  37708. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  37709. }
  37710. }
  37711. // Point size
  37712. if (this.pointsCloud) {
  37713. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37714. }
  37715. if (defines.SPECULARTERM) {
  37716. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  37717. }
  37718. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  37719. // Diffuse
  37720. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  37721. }
  37722. // Textures
  37723. if (scene.texturesEnabled) {
  37724. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37725. effect.setTexture("diffuseSampler", this._diffuseTexture);
  37726. }
  37727. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37728. effect.setTexture("ambientSampler", this._ambientTexture);
  37729. }
  37730. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37731. effect.setTexture("opacitySampler", this._opacityTexture);
  37732. }
  37733. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37734. if (this._reflectionTexture.isCube) {
  37735. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  37736. }
  37737. else {
  37738. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  37739. }
  37740. }
  37741. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37742. effect.setTexture("emissiveSampler", this._emissiveTexture);
  37743. }
  37744. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37745. effect.setTexture("lightmapSampler", this._lightmapTexture);
  37746. }
  37747. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37748. effect.setTexture("specularSampler", this._specularTexture);
  37749. }
  37750. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37751. effect.setTexture("bumpSampler", this._bumpTexture);
  37752. }
  37753. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37754. var depth = 1.0;
  37755. if (this._refractionTexture.isCube) {
  37756. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  37757. }
  37758. else {
  37759. effect.setTexture("refraction2DSampler", this._refractionTexture);
  37760. }
  37761. }
  37762. }
  37763. // Clip plane
  37764. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  37765. // Colors
  37766. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  37767. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  37768. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37769. }
  37770. if (mustRebind || !this.isFrozen) {
  37771. // Lights
  37772. if (scene.lightsEnabled && !this._disableLighting) {
  37773. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  37774. }
  37775. // View
  37776. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  37777. this.bindView(effect);
  37778. }
  37779. // Fog
  37780. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  37781. // Morph targets
  37782. if (defines.NUM_MORPH_INFLUENCERS) {
  37783. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  37784. }
  37785. // Log. depth
  37786. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  37787. // image processing
  37788. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  37789. this._imageProcessingConfiguration.bind(this._activeEffect);
  37790. }
  37791. }
  37792. this._uniformBuffer.update();
  37793. this._afterBind(mesh, this._activeEffect);
  37794. };
  37795. StandardMaterial.prototype.getAnimatables = function () {
  37796. var results = [];
  37797. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  37798. results.push(this._diffuseTexture);
  37799. }
  37800. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37801. results.push(this._ambientTexture);
  37802. }
  37803. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37804. results.push(this._opacityTexture);
  37805. }
  37806. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37807. results.push(this._reflectionTexture);
  37808. }
  37809. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37810. results.push(this._emissiveTexture);
  37811. }
  37812. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  37813. results.push(this._specularTexture);
  37814. }
  37815. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37816. results.push(this._bumpTexture);
  37817. }
  37818. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37819. results.push(this._lightmapTexture);
  37820. }
  37821. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37822. results.push(this._refractionTexture);
  37823. }
  37824. return results;
  37825. };
  37826. StandardMaterial.prototype.getActiveTextures = function () {
  37827. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37828. if (this._diffuseTexture) {
  37829. activeTextures.push(this._diffuseTexture);
  37830. }
  37831. if (this._ambientTexture) {
  37832. activeTextures.push(this._ambientTexture);
  37833. }
  37834. if (this._opacityTexture) {
  37835. activeTextures.push(this._opacityTexture);
  37836. }
  37837. if (this._reflectionTexture) {
  37838. activeTextures.push(this._reflectionTexture);
  37839. }
  37840. if (this._emissiveTexture) {
  37841. activeTextures.push(this._emissiveTexture);
  37842. }
  37843. if (this._specularTexture) {
  37844. activeTextures.push(this._specularTexture);
  37845. }
  37846. if (this._bumpTexture) {
  37847. activeTextures.push(this._bumpTexture);
  37848. }
  37849. if (this._lightmapTexture) {
  37850. activeTextures.push(this._lightmapTexture);
  37851. }
  37852. if (this._refractionTexture) {
  37853. activeTextures.push(this._refractionTexture);
  37854. }
  37855. return activeTextures;
  37856. };
  37857. StandardMaterial.prototype.hasTexture = function (texture) {
  37858. if (_super.prototype.hasTexture.call(this, texture)) {
  37859. return true;
  37860. }
  37861. if (this._diffuseTexture === texture) {
  37862. return true;
  37863. }
  37864. if (this._ambientTexture === texture) {
  37865. return true;
  37866. }
  37867. if (this._opacityTexture === texture) {
  37868. return true;
  37869. }
  37870. if (this._reflectionTexture === texture) {
  37871. return true;
  37872. }
  37873. if (this._emissiveTexture === texture) {
  37874. return true;
  37875. }
  37876. if (this._specularTexture === texture) {
  37877. return true;
  37878. }
  37879. if (this._bumpTexture === texture) {
  37880. return true;
  37881. }
  37882. if (this._lightmapTexture === texture) {
  37883. return true;
  37884. }
  37885. if (this._refractionTexture === texture) {
  37886. return true;
  37887. }
  37888. return false;
  37889. };
  37890. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37891. if (forceDisposeTextures) {
  37892. if (this._diffuseTexture) {
  37893. this._diffuseTexture.dispose();
  37894. }
  37895. if (this._ambientTexture) {
  37896. this._ambientTexture.dispose();
  37897. }
  37898. if (this._opacityTexture) {
  37899. this._opacityTexture.dispose();
  37900. }
  37901. if (this._reflectionTexture) {
  37902. this._reflectionTexture.dispose();
  37903. }
  37904. if (this._emissiveTexture) {
  37905. this._emissiveTexture.dispose();
  37906. }
  37907. if (this._specularTexture) {
  37908. this._specularTexture.dispose();
  37909. }
  37910. if (this._bumpTexture) {
  37911. this._bumpTexture.dispose();
  37912. }
  37913. if (this._lightmapTexture) {
  37914. this._lightmapTexture.dispose();
  37915. }
  37916. if (this._refractionTexture) {
  37917. this._refractionTexture.dispose();
  37918. }
  37919. }
  37920. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37921. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37922. }
  37923. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37924. };
  37925. StandardMaterial.prototype.clone = function (name) {
  37926. var _this = this;
  37927. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  37928. result.name = name;
  37929. result.id = name;
  37930. return result;
  37931. };
  37932. StandardMaterial.prototype.serialize = function () {
  37933. return BABYLON.SerializationHelper.Serialize(this);
  37934. };
  37935. // Statics
  37936. StandardMaterial.Parse = function (source, scene, rootUrl) {
  37937. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  37938. };
  37939. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  37940. get: function () {
  37941. return StandardMaterial._DiffuseTextureEnabled;
  37942. },
  37943. set: function (value) {
  37944. if (StandardMaterial._DiffuseTextureEnabled === value) {
  37945. return;
  37946. }
  37947. StandardMaterial._DiffuseTextureEnabled = value;
  37948. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37949. },
  37950. enumerable: true,
  37951. configurable: true
  37952. });
  37953. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  37954. get: function () {
  37955. return StandardMaterial._AmbientTextureEnabled;
  37956. },
  37957. set: function (value) {
  37958. if (StandardMaterial._AmbientTextureEnabled === value) {
  37959. return;
  37960. }
  37961. StandardMaterial._AmbientTextureEnabled = value;
  37962. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37963. },
  37964. enumerable: true,
  37965. configurable: true
  37966. });
  37967. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37968. get: function () {
  37969. return StandardMaterial._OpacityTextureEnabled;
  37970. },
  37971. set: function (value) {
  37972. if (StandardMaterial._OpacityTextureEnabled === value) {
  37973. return;
  37974. }
  37975. StandardMaterial._OpacityTextureEnabled = value;
  37976. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37977. },
  37978. enumerable: true,
  37979. configurable: true
  37980. });
  37981. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37982. get: function () {
  37983. return StandardMaterial._ReflectionTextureEnabled;
  37984. },
  37985. set: function (value) {
  37986. if (StandardMaterial._ReflectionTextureEnabled === value) {
  37987. return;
  37988. }
  37989. StandardMaterial._ReflectionTextureEnabled = value;
  37990. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37991. },
  37992. enumerable: true,
  37993. configurable: true
  37994. });
  37995. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  37996. get: function () {
  37997. return StandardMaterial._EmissiveTextureEnabled;
  37998. },
  37999. set: function (value) {
  38000. if (StandardMaterial._EmissiveTextureEnabled === value) {
  38001. return;
  38002. }
  38003. StandardMaterial._EmissiveTextureEnabled = value;
  38004. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38005. },
  38006. enumerable: true,
  38007. configurable: true
  38008. });
  38009. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  38010. get: function () {
  38011. return StandardMaterial._SpecularTextureEnabled;
  38012. },
  38013. set: function (value) {
  38014. if (StandardMaterial._SpecularTextureEnabled === value) {
  38015. return;
  38016. }
  38017. StandardMaterial._SpecularTextureEnabled = value;
  38018. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38019. },
  38020. enumerable: true,
  38021. configurable: true
  38022. });
  38023. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  38024. get: function () {
  38025. return StandardMaterial._BumpTextureEnabled;
  38026. },
  38027. set: function (value) {
  38028. if (StandardMaterial._BumpTextureEnabled === value) {
  38029. return;
  38030. }
  38031. StandardMaterial._BumpTextureEnabled = value;
  38032. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38033. },
  38034. enumerable: true,
  38035. configurable: true
  38036. });
  38037. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  38038. get: function () {
  38039. return StandardMaterial._LightmapTextureEnabled;
  38040. },
  38041. set: function (value) {
  38042. if (StandardMaterial._LightmapTextureEnabled === value) {
  38043. return;
  38044. }
  38045. StandardMaterial._LightmapTextureEnabled = value;
  38046. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38047. },
  38048. enumerable: true,
  38049. configurable: true
  38050. });
  38051. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  38052. get: function () {
  38053. return StandardMaterial._RefractionTextureEnabled;
  38054. },
  38055. set: function (value) {
  38056. if (StandardMaterial._RefractionTextureEnabled === value) {
  38057. return;
  38058. }
  38059. StandardMaterial._RefractionTextureEnabled = value;
  38060. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38061. },
  38062. enumerable: true,
  38063. configurable: true
  38064. });
  38065. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  38066. get: function () {
  38067. return StandardMaterial._ColorGradingTextureEnabled;
  38068. },
  38069. set: function (value) {
  38070. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  38071. return;
  38072. }
  38073. StandardMaterial._ColorGradingTextureEnabled = value;
  38074. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  38075. },
  38076. enumerable: true,
  38077. configurable: true
  38078. });
  38079. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  38080. get: function () {
  38081. return StandardMaterial._FresnelEnabled;
  38082. },
  38083. set: function (value) {
  38084. if (StandardMaterial._FresnelEnabled === value) {
  38085. return;
  38086. }
  38087. StandardMaterial._FresnelEnabled = value;
  38088. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  38089. },
  38090. enumerable: true,
  38091. configurable: true
  38092. });
  38093. // Flags used to enable or disable a type of texture for all Standard Materials
  38094. StandardMaterial._DiffuseTextureEnabled = true;
  38095. StandardMaterial._AmbientTextureEnabled = true;
  38096. StandardMaterial._OpacityTextureEnabled = true;
  38097. StandardMaterial._ReflectionTextureEnabled = true;
  38098. StandardMaterial._EmissiveTextureEnabled = true;
  38099. StandardMaterial._SpecularTextureEnabled = true;
  38100. StandardMaterial._BumpTextureEnabled = true;
  38101. StandardMaterial._LightmapTextureEnabled = true;
  38102. StandardMaterial._RefractionTextureEnabled = true;
  38103. StandardMaterial._ColorGradingTextureEnabled = true;
  38104. StandardMaterial._FresnelEnabled = true;
  38105. __decorate([
  38106. BABYLON.serializeAsTexture("diffuseTexture")
  38107. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  38108. __decorate([
  38109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  38110. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  38111. __decorate([
  38112. BABYLON.serializeAsTexture("ambientTexture")
  38113. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  38114. __decorate([
  38115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38116. ], StandardMaterial.prototype, "ambientTexture", void 0);
  38117. __decorate([
  38118. BABYLON.serializeAsTexture("opacityTexture")
  38119. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  38120. __decorate([
  38121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  38122. ], StandardMaterial.prototype, "opacityTexture", void 0);
  38123. __decorate([
  38124. BABYLON.serializeAsTexture("reflectionTexture")
  38125. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  38126. __decorate([
  38127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38128. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  38129. __decorate([
  38130. BABYLON.serializeAsTexture("emissiveTexture")
  38131. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  38132. __decorate([
  38133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38134. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  38135. __decorate([
  38136. BABYLON.serializeAsTexture("specularTexture")
  38137. ], StandardMaterial.prototype, "_specularTexture", void 0);
  38138. __decorate([
  38139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38140. ], StandardMaterial.prototype, "specularTexture", void 0);
  38141. __decorate([
  38142. BABYLON.serializeAsTexture("bumpTexture")
  38143. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  38144. __decorate([
  38145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38146. ], StandardMaterial.prototype, "bumpTexture", void 0);
  38147. __decorate([
  38148. BABYLON.serializeAsTexture("lightmapTexture")
  38149. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  38150. __decorate([
  38151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38152. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  38153. __decorate([
  38154. BABYLON.serializeAsTexture("refractionTexture")
  38155. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  38156. __decorate([
  38157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38158. ], StandardMaterial.prototype, "refractionTexture", void 0);
  38159. __decorate([
  38160. BABYLON.serializeAsColor3("ambient")
  38161. ], StandardMaterial.prototype, "ambientColor", void 0);
  38162. __decorate([
  38163. BABYLON.serializeAsColor3("diffuse")
  38164. ], StandardMaterial.prototype, "diffuseColor", void 0);
  38165. __decorate([
  38166. BABYLON.serializeAsColor3("specular")
  38167. ], StandardMaterial.prototype, "specularColor", void 0);
  38168. __decorate([
  38169. BABYLON.serializeAsColor3("emissive")
  38170. ], StandardMaterial.prototype, "emissiveColor", void 0);
  38171. __decorate([
  38172. BABYLON.serialize()
  38173. ], StandardMaterial.prototype, "specularPower", void 0);
  38174. __decorate([
  38175. BABYLON.serialize("useAlphaFromDiffuseTexture")
  38176. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  38177. __decorate([
  38178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38179. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  38180. __decorate([
  38181. BABYLON.serialize("useEmissiveAsIllumination")
  38182. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  38183. __decorate([
  38184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38185. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  38186. __decorate([
  38187. BABYLON.serialize("linkEmissiveWithDiffuse")
  38188. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  38189. __decorate([
  38190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38191. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  38192. __decorate([
  38193. BABYLON.serialize("useSpecularOverAlpha")
  38194. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  38195. __decorate([
  38196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38197. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  38198. __decorate([
  38199. BABYLON.serialize("useReflectionOverAlpha")
  38200. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  38201. __decorate([
  38202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38203. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  38204. __decorate([
  38205. BABYLON.serialize("disableLighting")
  38206. ], StandardMaterial.prototype, "_disableLighting", void 0);
  38207. __decorate([
  38208. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38209. ], StandardMaterial.prototype, "disableLighting", void 0);
  38210. __decorate([
  38211. BABYLON.serialize("useParallax")
  38212. ], StandardMaterial.prototype, "_useParallax", void 0);
  38213. __decorate([
  38214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38215. ], StandardMaterial.prototype, "useParallax", void 0);
  38216. __decorate([
  38217. BABYLON.serialize("useParallaxOcclusion")
  38218. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  38219. __decorate([
  38220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38221. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  38222. __decorate([
  38223. BABYLON.serialize()
  38224. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  38225. __decorate([
  38226. BABYLON.serialize("roughness")
  38227. ], StandardMaterial.prototype, "_roughness", void 0);
  38228. __decorate([
  38229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38230. ], StandardMaterial.prototype, "roughness", void 0);
  38231. __decorate([
  38232. BABYLON.serialize()
  38233. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  38234. __decorate([
  38235. BABYLON.serialize()
  38236. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  38237. __decorate([
  38238. BABYLON.serialize("useLightmapAsShadowmap")
  38239. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  38240. __decorate([
  38241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38242. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38243. __decorate([
  38244. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  38245. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  38246. __decorate([
  38247. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38248. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  38249. __decorate([
  38250. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  38251. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  38252. __decorate([
  38253. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  38254. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  38255. __decorate([
  38256. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  38257. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  38258. __decorate([
  38259. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38260. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  38261. __decorate([
  38262. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  38263. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  38264. __decorate([
  38265. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38266. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  38267. __decorate([
  38268. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  38269. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  38270. __decorate([
  38271. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38272. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  38273. __decorate([
  38274. BABYLON.serialize("useReflectionFresnelFromSpecular")
  38275. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  38276. __decorate([
  38277. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38278. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  38279. __decorate([
  38280. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  38281. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  38282. __decorate([
  38283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38284. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  38285. __decorate([
  38286. BABYLON.serialize("maxSimultaneousLights")
  38287. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  38288. __decorate([
  38289. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38290. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  38291. __decorate([
  38292. BABYLON.serialize("invertNormalMapX")
  38293. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  38294. __decorate([
  38295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38296. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  38297. __decorate([
  38298. BABYLON.serialize("invertNormalMapY")
  38299. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  38300. __decorate([
  38301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38302. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  38303. __decorate([
  38304. BABYLON.serialize("twoSidedLighting")
  38305. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  38306. __decorate([
  38307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38308. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  38309. __decorate([
  38310. BABYLON.serialize()
  38311. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  38312. return StandardMaterial;
  38313. }(BABYLON.PushMaterial));
  38314. BABYLON.StandardMaterial = StandardMaterial;
  38315. })(BABYLON || (BABYLON = {}));
  38316. //# sourceMappingURL=babylon.standardMaterial.js.map
  38317. var BABYLON;
  38318. (function (BABYLON) {
  38319. var PBRMaterialDefines = /** @class */ (function (_super) {
  38320. __extends(PBRMaterialDefines, _super);
  38321. function PBRMaterialDefines() {
  38322. var _this = _super.call(this) || this;
  38323. _this.PBR = true;
  38324. _this.MAINUV1 = false;
  38325. _this.MAINUV2 = false;
  38326. _this.UV1 = false;
  38327. _this.UV2 = false;
  38328. _this.ALBEDO = false;
  38329. _this.ALBEDODIRECTUV = 0;
  38330. _this.VERTEXCOLOR = false;
  38331. _this.AMBIENT = false;
  38332. _this.AMBIENTDIRECTUV = 0;
  38333. _this.AMBIENTINGRAYSCALE = false;
  38334. _this.OPACITY = false;
  38335. _this.VERTEXALPHA = false;
  38336. _this.OPACITYDIRECTUV = 0;
  38337. _this.OPACITYRGB = false;
  38338. _this.ALPHATEST = false;
  38339. _this.DEPTHPREPASS = false;
  38340. _this.ALPHABLEND = false;
  38341. _this.ALPHAFROMALBEDO = false;
  38342. _this.ALPHATESTVALUE = 0.5;
  38343. _this.SPECULAROVERALPHA = false;
  38344. _this.RADIANCEOVERALPHA = false;
  38345. _this.ALPHAFRESNEL = false;
  38346. _this.LINEARALPHAFRESNEL = false;
  38347. _this.PREMULTIPLYALPHA = false;
  38348. _this.EMISSIVE = false;
  38349. _this.EMISSIVEDIRECTUV = 0;
  38350. _this.REFLECTIVITY = false;
  38351. _this.REFLECTIVITYDIRECTUV = 0;
  38352. _this.SPECULARTERM = false;
  38353. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  38354. _this.MICROSURFACEAUTOMATIC = false;
  38355. _this.LODBASEDMICROSFURACE = false;
  38356. _this.MICROSURFACEMAP = false;
  38357. _this.MICROSURFACEMAPDIRECTUV = 0;
  38358. _this.METALLICWORKFLOW = false;
  38359. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  38360. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  38361. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  38362. _this.AOSTOREINMETALMAPRED = false;
  38363. _this.ENVIRONMENTBRDF = false;
  38364. _this.NORMAL = false;
  38365. _this.TANGENT = false;
  38366. _this.BUMP = false;
  38367. _this.BUMPDIRECTUV = 0;
  38368. _this.PARALLAX = false;
  38369. _this.PARALLAXOCCLUSION = false;
  38370. _this.NORMALXYSCALE = true;
  38371. _this.LIGHTMAP = false;
  38372. _this.LIGHTMAPDIRECTUV = 0;
  38373. _this.USELIGHTMAPASSHADOWMAP = false;
  38374. _this.REFLECTION = false;
  38375. _this.REFLECTIONMAP_3D = false;
  38376. _this.REFLECTIONMAP_SPHERICAL = false;
  38377. _this.REFLECTIONMAP_PLANAR = false;
  38378. _this.REFLECTIONMAP_CUBIC = false;
  38379. _this.REFLECTIONMAP_PROJECTION = false;
  38380. _this.REFLECTIONMAP_SKYBOX = false;
  38381. _this.REFLECTIONMAP_EXPLICIT = false;
  38382. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38383. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38384. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38385. _this.INVERTCUBICMAP = false;
  38386. _this.USESPHERICALFROMREFLECTIONMAP = false;
  38387. _this.USESPHERICALINVERTEX = false;
  38388. _this.REFLECTIONMAP_OPPOSITEZ = false;
  38389. _this.LODINREFLECTIONALPHA = false;
  38390. _this.GAMMAREFLECTION = false;
  38391. _this.RADIANCEOCCLUSION = false;
  38392. _this.HORIZONOCCLUSION = false;
  38393. _this.REFRACTION = false;
  38394. _this.REFRACTIONMAP_3D = false;
  38395. _this.REFRACTIONMAP_OPPOSITEZ = false;
  38396. _this.LODINREFRACTIONALPHA = false;
  38397. _this.GAMMAREFRACTION = false;
  38398. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  38399. _this.INSTANCES = false;
  38400. _this.NUM_BONE_INFLUENCERS = 0;
  38401. _this.BonesPerMesh = 0;
  38402. _this.NONUNIFORMSCALING = false;
  38403. _this.MORPHTARGETS = false;
  38404. _this.MORPHTARGETS_NORMAL = false;
  38405. _this.MORPHTARGETS_TANGENT = false;
  38406. _this.NUM_MORPH_INFLUENCERS = 0;
  38407. _this.IMAGEPROCESSING = false;
  38408. _this.VIGNETTE = false;
  38409. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38410. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38411. _this.TONEMAPPING = false;
  38412. _this.CONTRAST = false;
  38413. _this.COLORCURVES = false;
  38414. _this.COLORGRADING = false;
  38415. _this.COLORGRADING3D = false;
  38416. _this.SAMPLER3DGREENDEPTH = false;
  38417. _this.SAMPLER3DBGRMAP = false;
  38418. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38419. _this.EXPOSURE = false;
  38420. _this.USEPHYSICALLIGHTFALLOFF = false;
  38421. _this.TWOSIDEDLIGHTING = false;
  38422. _this.SHADOWFLOAT = false;
  38423. _this.CLIPPLANE = false;
  38424. _this.POINTSIZE = false;
  38425. _this.FOG = false;
  38426. _this.LOGARITHMICDEPTH = false;
  38427. _this.FORCENORMALFORWARD = false;
  38428. _this.rebuild();
  38429. return _this;
  38430. }
  38431. PBRMaterialDefines.prototype.reset = function () {
  38432. _super.prototype.reset.call(this);
  38433. this.ALPHATESTVALUE = 0.5;
  38434. this.PBR = true;
  38435. };
  38436. return PBRMaterialDefines;
  38437. }(BABYLON.MaterialDefines));
  38438. /**
  38439. * The Physically based material base class of BJS.
  38440. *
  38441. * This offers the main features of a standard PBR material.
  38442. * For more information, please refer to the documentation :
  38443. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38444. */
  38445. var PBRBaseMaterial = /** @class */ (function (_super) {
  38446. __extends(PBRBaseMaterial, _super);
  38447. /**
  38448. * Instantiates a new PBRMaterial instance.
  38449. *
  38450. * @param name The material name
  38451. * @param scene The scene the material will be use in.
  38452. */
  38453. function PBRBaseMaterial(name, scene) {
  38454. var _this = _super.call(this, name, scene) || this;
  38455. /**
  38456. * Intensity of the direct lights e.g. the four lights available in your scene.
  38457. * This impacts both the direct diffuse and specular highlights.
  38458. */
  38459. _this._directIntensity = 1.0;
  38460. /**
  38461. * Intensity of the emissive part of the material.
  38462. * This helps controlling the emissive effect without modifying the emissive color.
  38463. */
  38464. _this._emissiveIntensity = 1.0;
  38465. /**
  38466. * Intensity of the environment e.g. how much the environment will light the object
  38467. * either through harmonics for rough material or through the refelction for shiny ones.
  38468. */
  38469. _this._environmentIntensity = 1.0;
  38470. /**
  38471. * This is a special control allowing the reduction of the specular highlights coming from the
  38472. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38473. */
  38474. _this._specularIntensity = 1.0;
  38475. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  38476. /**
  38477. * Debug Control allowing disabling the bump map on this material.
  38478. */
  38479. _this._disableBumpMap = false;
  38480. /**
  38481. * AKA Occlusion Texture Intensity in other nomenclature.
  38482. */
  38483. _this._ambientTextureStrength = 1.0;
  38484. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  38485. /**
  38486. * AKA Diffuse Color in other nomenclature.
  38487. */
  38488. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  38489. /**
  38490. * AKA Specular Color in other nomenclature.
  38491. */
  38492. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38493. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  38494. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  38495. /**
  38496. * AKA Glossiness in other nomenclature.
  38497. */
  38498. _this._microSurface = 0.9;
  38499. /**
  38500. * source material index of refraction (IOR)' / 'destination material IOR.
  38501. */
  38502. _this._indexOfRefraction = 0.66;
  38503. /**
  38504. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38505. */
  38506. _this._invertRefractionY = false;
  38507. /**
  38508. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38509. * Materials half opaque for instance using refraction could benefit from this control.
  38510. */
  38511. _this._linkRefractionWithTransparency = false;
  38512. _this._useLightmapAsShadowmap = false;
  38513. /**
  38514. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38515. * makes the reflect vector face the model (under horizon).
  38516. */
  38517. _this._useHorizonOcclusion = true;
  38518. /**
  38519. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38520. * too much the area relying on ambient texture to define their ambient occlusion.
  38521. */
  38522. _this._useRadianceOcclusion = true;
  38523. /**
  38524. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  38525. */
  38526. _this._useAlphaFromAlbedoTexture = false;
  38527. /**
  38528. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38529. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38530. */
  38531. _this._useSpecularOverAlpha = true;
  38532. /**
  38533. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38534. */
  38535. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  38536. /**
  38537. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38538. */
  38539. _this._useRoughnessFromMetallicTextureAlpha = true;
  38540. /**
  38541. * Specifies if the metallic texture contains the roughness information in its green channel.
  38542. */
  38543. _this._useRoughnessFromMetallicTextureGreen = false;
  38544. /**
  38545. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38546. */
  38547. _this._useMetallnessFromMetallicTextureBlue = false;
  38548. /**
  38549. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38550. */
  38551. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  38552. /**
  38553. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38554. */
  38555. _this._useAmbientInGrayScale = false;
  38556. /**
  38557. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38558. * The material will try to infer what glossiness each pixel should be.
  38559. */
  38560. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  38561. /**
  38562. * BJS is using an harcoded light falloff based on a manually sets up range.
  38563. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38564. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38565. */
  38566. _this._usePhysicalLightFalloff = true;
  38567. /**
  38568. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38569. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38570. */
  38571. _this._useRadianceOverAlpha = true;
  38572. /**
  38573. * Allows using the bump map in parallax mode.
  38574. */
  38575. _this._useParallax = false;
  38576. /**
  38577. * Allows using the bump map in parallax occlusion mode.
  38578. */
  38579. _this._useParallaxOcclusion = false;
  38580. /**
  38581. * Controls the scale bias of the parallax mode.
  38582. */
  38583. _this._parallaxScaleBias = 0.05;
  38584. /**
  38585. * If sets to true, disables all the lights affecting the material.
  38586. */
  38587. _this._disableLighting = false;
  38588. /**
  38589. * Number of Simultaneous lights allowed on the material.
  38590. */
  38591. _this._maxSimultaneousLights = 4;
  38592. /**
  38593. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  38594. */
  38595. _this._invertNormalMapX = false;
  38596. /**
  38597. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  38598. */
  38599. _this._invertNormalMapY = false;
  38600. /**
  38601. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38602. */
  38603. _this._twoSidedLighting = false;
  38604. /**
  38605. * Defines the alpha limits in alpha test mode.
  38606. */
  38607. _this._alphaCutOff = 0.4;
  38608. /**
  38609. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38610. */
  38611. _this._forceAlphaTest = false;
  38612. /**
  38613. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38614. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38615. */
  38616. _this._useAlphaFresnel = false;
  38617. /**
  38618. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38619. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38620. */
  38621. _this._useLinearAlphaFresnel = false;
  38622. /**
  38623. * The transparency mode of the material.
  38624. */
  38625. _this._transparencyMode = null;
  38626. /**
  38627. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  38628. * from cos thetav and roughness:
  38629. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  38630. */
  38631. _this._environmentBRDFTexture = null;
  38632. /**
  38633. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38634. */
  38635. _this._forceIrradianceInFragment = false;
  38636. /**
  38637. * Force normal to face away from face.
  38638. */
  38639. _this._forceNormalForward = false;
  38640. /**
  38641. * Force metallic workflow.
  38642. */
  38643. _this._forceMetallicWorkflow = false;
  38644. _this._renderTargets = new BABYLON.SmartArray(16);
  38645. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38646. // Setup the default processing configuration to the scene.
  38647. _this._attachImageProcessingConfiguration(null);
  38648. _this.getRenderTargetTextures = function () {
  38649. _this._renderTargets.reset();
  38650. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38651. _this._renderTargets.push(_this._reflectionTexture);
  38652. }
  38653. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38654. _this._renderTargets.push(_this._refractionTexture);
  38655. }
  38656. return _this._renderTargets;
  38657. };
  38658. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38659. return _this;
  38660. }
  38661. /**
  38662. * Attaches a new image processing configuration to the PBR Material.
  38663. * @param configuration
  38664. */
  38665. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38666. var _this = this;
  38667. if (configuration === this._imageProcessingConfiguration) {
  38668. return;
  38669. }
  38670. // Detaches observer.
  38671. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38672. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38673. }
  38674. // Pick the scene configuration if needed.
  38675. if (!configuration) {
  38676. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38677. }
  38678. else {
  38679. this._imageProcessingConfiguration = configuration;
  38680. }
  38681. // Attaches observer.
  38682. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38683. _this._markAllSubMeshesAsImageProcessingDirty();
  38684. });
  38685. };
  38686. PBRBaseMaterial.prototype.getClassName = function () {
  38687. return "PBRBaseMaterial";
  38688. };
  38689. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38690. get: function () {
  38691. return this._useLogarithmicDepth;
  38692. },
  38693. set: function (value) {
  38694. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38695. },
  38696. enumerable: true,
  38697. configurable: true
  38698. });
  38699. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  38700. /**
  38701. * Gets the current transparency mode.
  38702. */
  38703. get: function () {
  38704. return this._transparencyMode;
  38705. },
  38706. /**
  38707. * Sets the transparency mode of the material.
  38708. */
  38709. set: function (value) {
  38710. if (this._transparencyMode === value) {
  38711. return;
  38712. }
  38713. this._transparencyMode = value;
  38714. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  38715. this._markAllSubMeshesAsTexturesAndMiscDirty();
  38716. },
  38717. enumerable: true,
  38718. configurable: true
  38719. });
  38720. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  38721. /**
  38722. * Returns true if alpha blending should be disabled.
  38723. */
  38724. get: function () {
  38725. return (this._linkRefractionWithTransparency ||
  38726. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  38727. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38728. },
  38729. enumerable: true,
  38730. configurable: true
  38731. });
  38732. /**
  38733. * Specifies whether or not this material should be rendered in alpha blend mode.
  38734. */
  38735. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38736. if (this._disableAlphaBlending) {
  38737. return false;
  38738. }
  38739. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  38740. };
  38741. /**
  38742. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  38743. */
  38744. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  38745. if (this._disableAlphaBlending) {
  38746. return false;
  38747. }
  38748. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  38749. };
  38750. /**
  38751. * Specifies whether or not this material should be rendered in alpha test mode.
  38752. */
  38753. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38754. if (this._forceAlphaTest) {
  38755. return true;
  38756. }
  38757. if (this._linkRefractionWithTransparency) {
  38758. return false;
  38759. }
  38760. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38761. };
  38762. /**
  38763. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  38764. */
  38765. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38766. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38767. };
  38768. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38769. return this._albedoTexture;
  38770. };
  38771. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38772. var _this = this;
  38773. if (subMesh.effect && this.isFrozen) {
  38774. if (this._wasPreviouslyReady) {
  38775. return true;
  38776. }
  38777. }
  38778. if (!subMesh._materialDefines) {
  38779. subMesh._materialDefines = new PBRMaterialDefines();
  38780. }
  38781. var scene = this.getScene();
  38782. var defines = subMesh._materialDefines;
  38783. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38784. if (defines._renderId === scene.getRenderId()) {
  38785. return true;
  38786. }
  38787. }
  38788. var engine = scene.getEngine();
  38789. // Lights
  38790. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38791. defines._needNormals = true;
  38792. // Textures
  38793. if (defines._areTexturesDirty) {
  38794. defines._needUVs = false;
  38795. if (scene.texturesEnabled) {
  38796. if (scene.getEngine().getCaps().textureLOD) {
  38797. defines.LODBASEDMICROSFURACE = true;
  38798. }
  38799. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38800. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38801. return false;
  38802. }
  38803. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  38804. }
  38805. else {
  38806. defines.ALBEDO = false;
  38807. }
  38808. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38809. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38810. return false;
  38811. }
  38812. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38813. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38814. }
  38815. else {
  38816. defines.AMBIENT = false;
  38817. }
  38818. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38819. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38820. return false;
  38821. }
  38822. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38823. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38824. }
  38825. else {
  38826. defines.OPACITY = false;
  38827. }
  38828. var reflectionTexture = this._getReflectionTexture();
  38829. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38830. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38831. return false;
  38832. }
  38833. defines.REFLECTION = true;
  38834. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  38835. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  38836. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  38837. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38838. defines.INVERTCUBICMAP = true;
  38839. }
  38840. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38841. switch (reflectionTexture.coordinatesMode) {
  38842. case BABYLON.Texture.CUBIC_MODE:
  38843. case BABYLON.Texture.INVCUBIC_MODE:
  38844. defines.REFLECTIONMAP_CUBIC = true;
  38845. break;
  38846. case BABYLON.Texture.EXPLICIT_MODE:
  38847. defines.REFLECTIONMAP_EXPLICIT = true;
  38848. break;
  38849. case BABYLON.Texture.PLANAR_MODE:
  38850. defines.REFLECTIONMAP_PLANAR = true;
  38851. break;
  38852. case BABYLON.Texture.PROJECTION_MODE:
  38853. defines.REFLECTIONMAP_PROJECTION = true;
  38854. break;
  38855. case BABYLON.Texture.SKYBOX_MODE:
  38856. defines.REFLECTIONMAP_SKYBOX = true;
  38857. break;
  38858. case BABYLON.Texture.SPHERICAL_MODE:
  38859. defines.REFLECTIONMAP_SPHERICAL = true;
  38860. break;
  38861. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38862. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38863. break;
  38864. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38865. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38866. break;
  38867. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38868. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38869. break;
  38870. }
  38871. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  38872. if (reflectionTexture.sphericalPolynomial) {
  38873. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38874. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  38875. defines.USESPHERICALINVERTEX = false;
  38876. }
  38877. else {
  38878. defines.USESPHERICALINVERTEX = true;
  38879. }
  38880. }
  38881. }
  38882. }
  38883. else {
  38884. defines.REFLECTION = false;
  38885. defines.REFLECTIONMAP_3D = false;
  38886. defines.REFLECTIONMAP_SPHERICAL = false;
  38887. defines.REFLECTIONMAP_PLANAR = false;
  38888. defines.REFLECTIONMAP_CUBIC = false;
  38889. defines.REFLECTIONMAP_PROJECTION = false;
  38890. defines.REFLECTIONMAP_SKYBOX = false;
  38891. defines.REFLECTIONMAP_EXPLICIT = false;
  38892. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38893. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38894. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38895. defines.INVERTCUBICMAP = false;
  38896. defines.USESPHERICALFROMREFLECTIONMAP = false;
  38897. defines.USESPHERICALINVERTEX = false;
  38898. defines.REFLECTIONMAP_OPPOSITEZ = false;
  38899. defines.LODINREFLECTIONALPHA = false;
  38900. defines.GAMMAREFLECTION = false;
  38901. }
  38902. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38903. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38904. return false;
  38905. }
  38906. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38907. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38908. }
  38909. else {
  38910. defines.LIGHTMAP = false;
  38911. }
  38912. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38913. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38914. return false;
  38915. }
  38916. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38917. }
  38918. else {
  38919. defines.EMISSIVE = false;
  38920. }
  38921. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38922. if (this._metallicTexture) {
  38923. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38924. return false;
  38925. }
  38926. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  38927. defines.METALLICWORKFLOW = true;
  38928. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38929. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38930. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38931. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38932. }
  38933. else if (this._reflectivityTexture) {
  38934. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38935. return false;
  38936. }
  38937. defines.METALLICWORKFLOW = false;
  38938. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  38939. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38940. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38941. }
  38942. else {
  38943. defines.METALLICWORKFLOW = false;
  38944. defines.REFLECTIVITY = false;
  38945. }
  38946. if (this._microSurfaceTexture) {
  38947. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38948. return false;
  38949. }
  38950. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  38951. }
  38952. else {
  38953. defines.MICROSURFACEMAP = false;
  38954. }
  38955. }
  38956. else {
  38957. defines.REFLECTIVITY = false;
  38958. defines.MICROSURFACEMAP = false;
  38959. }
  38960. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38961. // Bump texure can not be none blocking.
  38962. if (!this._bumpTexture.isReady()) {
  38963. return false;
  38964. }
  38965. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38966. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38967. defines.PARALLAX = true;
  38968. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38969. }
  38970. else {
  38971. defines.PARALLAX = false;
  38972. }
  38973. }
  38974. else {
  38975. defines.BUMP = false;
  38976. }
  38977. var refractionTexture = this._getRefractionTexture();
  38978. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38979. if (!refractionTexture.isReadyOrNotBlocking()) {
  38980. return false;
  38981. }
  38982. defines.REFRACTION = true;
  38983. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38984. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38985. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  38986. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  38987. if (this._linkRefractionWithTransparency) {
  38988. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38989. }
  38990. }
  38991. else {
  38992. defines.REFRACTION = false;
  38993. }
  38994. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38995. // This is blocking.
  38996. if (!this._environmentBRDFTexture.isReady()) {
  38997. return false;
  38998. }
  38999. defines.ENVIRONMENTBRDF = true;
  39000. }
  39001. else {
  39002. defines.ENVIRONMENTBRDF = false;
  39003. }
  39004. if (this._shouldUseAlphaFromAlbedoTexture()) {
  39005. defines.ALPHAFROMALBEDO = true;
  39006. }
  39007. else {
  39008. defines.ALPHAFROMALBEDO = false;
  39009. }
  39010. }
  39011. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39012. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  39013. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  39014. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  39015. defines.METALLICWORKFLOW = true;
  39016. }
  39017. else {
  39018. defines.METALLICWORKFLOW = false;
  39019. }
  39020. if (!this.backFaceCulling && this._twoSidedLighting) {
  39021. defines.TWOSIDEDLIGHTING = true;
  39022. }
  39023. else {
  39024. defines.TWOSIDEDLIGHTING = false;
  39025. }
  39026. defines.ALPHATESTVALUE = this._alphaCutOff;
  39027. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39028. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  39029. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  39030. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  39031. }
  39032. if (defines._areImageProcessingDirty) {
  39033. if (!this._imageProcessingConfiguration.isReady()) {
  39034. return false;
  39035. }
  39036. this._imageProcessingConfiguration.prepareDefines(defines);
  39037. }
  39038. defines.FORCENORMALFORWARD = this._forceNormalForward;
  39039. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  39040. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  39041. // Misc.
  39042. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  39043. // Values that need to be evaluated on every frame
  39044. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false);
  39045. // Attribs
  39046. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  39047. var bufferMesh = null;
  39048. if (mesh instanceof BABYLON.InstancedMesh) {
  39049. bufferMesh = mesh.sourceMesh;
  39050. }
  39051. else if (mesh instanceof BABYLON.Mesh) {
  39052. bufferMesh = mesh;
  39053. }
  39054. if (bufferMesh) {
  39055. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39056. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  39057. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  39058. var normals = normalVertexBuffer.getData();
  39059. var vertexBufferOffset = normalVertexBuffer.getOffset();
  39060. var strideSize = normalVertexBuffer.getStrideSize();
  39061. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  39062. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  39063. defines.NORMAL = false;
  39064. }
  39065. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39066. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  39067. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  39068. var tangents = tangentVertexBuffer.getData();
  39069. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  39070. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  39071. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  39072. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  39073. defines.TANGENT = false;
  39074. }
  39075. }
  39076. }
  39077. else {
  39078. if (!scene.getEngine().getCaps().standardDerivatives) {
  39079. bufferMesh.createNormals(true);
  39080. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  39081. }
  39082. }
  39083. }
  39084. }
  39085. // Get correct effect
  39086. if (defines.isDirty) {
  39087. defines.markAsProcessed();
  39088. scene.resetCachedMaterial();
  39089. // Fallbacks
  39090. var fallbacks = new BABYLON.EffectFallbacks();
  39091. var fallbackRank = 0;
  39092. if (defines.USESPHERICALINVERTEX) {
  39093. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  39094. }
  39095. if (defines.FOG) {
  39096. fallbacks.addFallback(fallbackRank, "FOG");
  39097. }
  39098. if (defines.POINTSIZE) {
  39099. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  39100. }
  39101. if (defines.LOGARITHMICDEPTH) {
  39102. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  39103. }
  39104. if (defines.PARALLAX) {
  39105. fallbacks.addFallback(fallbackRank, "PARALLAX");
  39106. }
  39107. if (defines.PARALLAXOCCLUSION) {
  39108. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  39109. }
  39110. if (defines.ENVIRONMENTBRDF) {
  39111. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  39112. }
  39113. if (defines.TANGENT) {
  39114. fallbacks.addFallback(fallbackRank++, "TANGENT");
  39115. }
  39116. if (defines.BUMP) {
  39117. fallbacks.addFallback(fallbackRank++, "BUMP");
  39118. }
  39119. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  39120. if (defines.SPECULARTERM) {
  39121. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  39122. }
  39123. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  39124. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  39125. }
  39126. if (defines.LIGHTMAP) {
  39127. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  39128. }
  39129. if (defines.NORMAL) {
  39130. fallbacks.addFallback(fallbackRank++, "NORMAL");
  39131. }
  39132. if (defines.AMBIENT) {
  39133. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  39134. }
  39135. if (defines.EMISSIVE) {
  39136. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  39137. }
  39138. if (defines.VERTEXCOLOR) {
  39139. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  39140. }
  39141. if (defines.NUM_BONE_INFLUENCERS > 0) {
  39142. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  39143. }
  39144. if (defines.MORPHTARGETS) {
  39145. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  39146. }
  39147. //Attributes
  39148. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39149. if (defines.NORMAL) {
  39150. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39151. }
  39152. if (defines.TANGENT) {
  39153. attribs.push(BABYLON.VertexBuffer.TangentKind);
  39154. }
  39155. if (defines.UV1) {
  39156. attribs.push(BABYLON.VertexBuffer.UVKind);
  39157. }
  39158. if (defines.UV2) {
  39159. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39160. }
  39161. if (defines.VERTEXCOLOR) {
  39162. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39163. }
  39164. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39165. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39166. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39167. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  39168. "vFogInfos", "vFogColor", "pointSize",
  39169. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39170. "mBones",
  39171. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  39172. "vLightingIntensity",
  39173. "logarithmicDepthConstant",
  39174. "vSphericalX", "vSphericalY", "vSphericalZ",
  39175. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  39176. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  39177. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  39178. "vTangentSpaceParams"
  39179. ];
  39180. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  39181. "bumpSampler", "lightmapSampler", "opacitySampler",
  39182. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  39183. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  39184. "microSurfaceSampler", "environmentBrdfSampler"];
  39185. var uniformBuffers = ["Material", "Scene"];
  39186. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39187. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39188. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39189. uniformsNames: uniforms,
  39190. uniformBuffersNames: uniformBuffers,
  39191. samplers: samplers,
  39192. defines: defines,
  39193. maxSimultaneousLights: this._maxSimultaneousLights
  39194. });
  39195. var onCompiled = function (effect) {
  39196. if (_this.onCompiled) {
  39197. _this.onCompiled(effect);
  39198. }
  39199. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  39200. };
  39201. var join = defines.toString();
  39202. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  39203. attributes: attribs,
  39204. uniformsNames: uniforms,
  39205. uniformBuffersNames: uniformBuffers,
  39206. samplers: samplers,
  39207. defines: join,
  39208. fallbacks: fallbacks,
  39209. onCompiled: onCompiled,
  39210. onError: this.onError,
  39211. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39212. }, engine), defines);
  39213. this.buildUniformLayout();
  39214. }
  39215. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39216. return false;
  39217. }
  39218. defines._renderId = scene.getRenderId();
  39219. this._wasPreviouslyReady = true;
  39220. return true;
  39221. };
  39222. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  39223. // Order is important !
  39224. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  39225. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  39226. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39227. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39228. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39229. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  39230. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  39231. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39232. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39233. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39234. this._uniformBuffer.addUniform("albedoMatrix", 16);
  39235. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39236. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39237. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39238. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39239. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  39240. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  39241. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39242. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39243. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39244. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39245. this._uniformBuffer.addUniform("vReflectionColor", 3);
  39246. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  39247. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  39248. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  39249. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  39250. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  39251. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39252. this._uniformBuffer.addUniform("pointSize", 1);
  39253. this._uniformBuffer.create();
  39254. };
  39255. PBRBaseMaterial.prototype.unbind = function () {
  39256. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39257. this._uniformBuffer.setTexture("reflectionSampler", null);
  39258. }
  39259. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39260. this._uniformBuffer.setTexture("refractionSampler", null);
  39261. }
  39262. _super.prototype.unbind.call(this);
  39263. };
  39264. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39265. this._activeEffect.setMatrix("world", world);
  39266. };
  39267. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39268. var scene = this.getScene();
  39269. var defines = subMesh._materialDefines;
  39270. if (!defines) {
  39271. return;
  39272. }
  39273. var effect = subMesh.effect;
  39274. if (!effect) {
  39275. return;
  39276. }
  39277. this._activeEffect = effect;
  39278. // Matrices
  39279. this.bindOnlyWorldMatrix(world);
  39280. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39281. // Bones
  39282. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  39283. var reflectionTexture = null;
  39284. if (mustRebind) {
  39285. this._uniformBuffer.bindToEffect(effect, "Material");
  39286. this.bindViewProjection(effect);
  39287. reflectionTexture = this._getReflectionTexture();
  39288. var refractionTexture = this._getRefractionTexture();
  39289. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39290. // Texture uniforms
  39291. if (scene.texturesEnabled) {
  39292. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39293. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  39294. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  39295. }
  39296. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39297. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  39298. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39299. }
  39300. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39301. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39302. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39303. }
  39304. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39305. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  39306. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  39307. var polynomials = reflectionTexture.sphericalPolynomial;
  39308. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  39309. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  39310. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  39311. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  39312. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  39313. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  39314. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  39315. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  39316. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  39317. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  39318. }
  39319. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  39320. }
  39321. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39322. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39323. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39324. }
  39325. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39326. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39327. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39328. }
  39329. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39330. if (this._metallicTexture) {
  39331. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  39332. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  39333. }
  39334. else if (this._reflectivityTexture) {
  39335. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  39336. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  39337. }
  39338. if (this._microSurfaceTexture) {
  39339. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  39340. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  39341. }
  39342. }
  39343. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39344. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  39345. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39346. if (scene._mirroredCameraPosition) {
  39347. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39348. }
  39349. else {
  39350. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39351. }
  39352. }
  39353. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39354. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  39355. var depth = 1.0;
  39356. if (!refractionTexture.isCube) {
  39357. if (refractionTexture.depth) {
  39358. depth = refractionTexture.depth;
  39359. }
  39360. }
  39361. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  39362. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  39363. }
  39364. }
  39365. // Point size
  39366. if (this.pointsCloud) {
  39367. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39368. }
  39369. // Colors
  39370. if (defines.METALLICWORKFLOW) {
  39371. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  39372. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  39373. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  39374. }
  39375. else {
  39376. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  39377. }
  39378. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  39379. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  39380. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  39381. // Misc
  39382. this._lightingInfos.x = this._directIntensity;
  39383. this._lightingInfos.y = this._emissiveIntensity;
  39384. this._lightingInfos.z = this._environmentIntensity;
  39385. this._lightingInfos.w = this._specularIntensity;
  39386. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  39387. }
  39388. // Textures
  39389. if (scene.texturesEnabled) {
  39390. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39391. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  39392. }
  39393. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39394. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  39395. }
  39396. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39397. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  39398. }
  39399. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39400. if (defines.LODBASEDMICROSFURACE) {
  39401. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  39402. }
  39403. else {
  39404. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  39405. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  39406. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  39407. }
  39408. }
  39409. if (defines.ENVIRONMENTBRDF) {
  39410. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  39411. }
  39412. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39413. if (defines.LODBASEDMICROSFURACE) {
  39414. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  39415. }
  39416. else {
  39417. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  39418. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  39419. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  39420. }
  39421. }
  39422. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39423. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  39424. }
  39425. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39426. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  39427. }
  39428. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39429. if (this._metallicTexture) {
  39430. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  39431. }
  39432. else if (this._reflectivityTexture) {
  39433. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  39434. }
  39435. if (this._microSurfaceTexture) {
  39436. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  39437. }
  39438. }
  39439. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39440. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  39441. }
  39442. }
  39443. // Clip plane
  39444. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  39445. // Colors
  39446. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  39447. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  39448. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  39449. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  39450. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39451. }
  39452. if (mustRebind || !this.isFrozen) {
  39453. // Lights
  39454. if (scene.lightsEnabled && !this._disableLighting) {
  39455. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  39456. }
  39457. // View
  39458. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  39459. this.bindView(effect);
  39460. }
  39461. // Fog
  39462. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  39463. // Morph targets
  39464. if (defines.NUM_MORPH_INFLUENCERS) {
  39465. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  39466. }
  39467. // image processing
  39468. this._imageProcessingConfiguration.bind(this._activeEffect);
  39469. // Log. depth
  39470. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  39471. }
  39472. this._uniformBuffer.update();
  39473. this._afterBind(mesh);
  39474. };
  39475. PBRBaseMaterial.prototype.getAnimatables = function () {
  39476. var results = [];
  39477. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  39478. results.push(this._albedoTexture);
  39479. }
  39480. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39481. results.push(this._ambientTexture);
  39482. }
  39483. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39484. results.push(this._opacityTexture);
  39485. }
  39486. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39487. results.push(this._reflectionTexture);
  39488. }
  39489. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39490. results.push(this._emissiveTexture);
  39491. }
  39492. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  39493. results.push(this._metallicTexture);
  39494. }
  39495. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  39496. results.push(this._reflectivityTexture);
  39497. }
  39498. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39499. results.push(this._bumpTexture);
  39500. }
  39501. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39502. results.push(this._lightmapTexture);
  39503. }
  39504. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39505. results.push(this._refractionTexture);
  39506. }
  39507. return results;
  39508. };
  39509. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  39510. if (this._reflectionTexture) {
  39511. return this._reflectionTexture;
  39512. }
  39513. return this.getScene().environmentTexture;
  39514. };
  39515. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  39516. if (this._refractionTexture) {
  39517. return this._refractionTexture;
  39518. }
  39519. if (this._linkRefractionWithTransparency) {
  39520. return this.getScene().environmentTexture;
  39521. }
  39522. return null;
  39523. };
  39524. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39525. if (forceDisposeTextures) {
  39526. if (this._albedoTexture) {
  39527. this._albedoTexture.dispose();
  39528. }
  39529. if (this._ambientTexture) {
  39530. this._ambientTexture.dispose();
  39531. }
  39532. if (this._opacityTexture) {
  39533. this._opacityTexture.dispose();
  39534. }
  39535. if (this._reflectionTexture) {
  39536. this._reflectionTexture.dispose();
  39537. }
  39538. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  39539. this._environmentBRDFTexture.dispose();
  39540. }
  39541. if (this._emissiveTexture) {
  39542. this._emissiveTexture.dispose();
  39543. }
  39544. if (this._metallicTexture) {
  39545. this._metallicTexture.dispose();
  39546. }
  39547. if (this._reflectivityTexture) {
  39548. this._reflectivityTexture.dispose();
  39549. }
  39550. if (this._bumpTexture) {
  39551. this._bumpTexture.dispose();
  39552. }
  39553. if (this._lightmapTexture) {
  39554. this._lightmapTexture.dispose();
  39555. }
  39556. if (this._refractionTexture) {
  39557. this._refractionTexture.dispose();
  39558. }
  39559. }
  39560. this._renderTargets.dispose();
  39561. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39562. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39563. }
  39564. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39565. };
  39566. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  39567. __decorate([
  39568. BABYLON.serializeAsImageProcessingConfiguration()
  39569. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  39570. __decorate([
  39571. BABYLON.serialize()
  39572. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  39573. __decorate([
  39574. BABYLON.serialize()
  39575. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  39576. return PBRBaseMaterial;
  39577. }(BABYLON.PushMaterial));
  39578. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  39579. })(BABYLON || (BABYLON = {}));
  39580. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  39581. var BABYLON;
  39582. (function (BABYLON) {
  39583. /**
  39584. * The Physically based simple base material of BJS.
  39585. *
  39586. * This enables better naming and convention enforcements on top of the pbrMaterial.
  39587. * It is used as the base class for both the specGloss and metalRough conventions.
  39588. */
  39589. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  39590. __extends(PBRBaseSimpleMaterial, _super);
  39591. /**
  39592. * Instantiates a new PBRMaterial instance.
  39593. *
  39594. * @param name The material name
  39595. * @param scene The scene the material will be use in.
  39596. */
  39597. function PBRBaseSimpleMaterial(name, scene) {
  39598. var _this = _super.call(this, name, scene) || this;
  39599. /**
  39600. * Number of Simultaneous lights allowed on the material.
  39601. */
  39602. _this.maxSimultaneousLights = 4;
  39603. /**
  39604. * If sets to true, disables all the lights affecting the material.
  39605. */
  39606. _this.disableLighting = false;
  39607. /**
  39608. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39609. */
  39610. _this.invertNormalMapX = false;
  39611. /**
  39612. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39613. */
  39614. _this.invertNormalMapY = false;
  39615. /**
  39616. * Emissivie color used to self-illuminate the model.
  39617. */
  39618. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39619. /**
  39620. * Occlusion Channel Strenght.
  39621. */
  39622. _this.occlusionStrength = 1.0;
  39623. _this.useLightmapAsShadowmap = false;
  39624. _this._useAlphaFromAlbedoTexture = true;
  39625. _this._useAmbientInGrayScale = true;
  39626. return _this;
  39627. }
  39628. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  39629. /**
  39630. * Gets the current double sided mode.
  39631. */
  39632. get: function () {
  39633. return this._twoSidedLighting;
  39634. },
  39635. /**
  39636. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39637. */
  39638. set: function (value) {
  39639. if (this._twoSidedLighting === value) {
  39640. return;
  39641. }
  39642. this._twoSidedLighting = value;
  39643. this.backFaceCulling = !value;
  39644. this._markAllSubMeshesAsTexturesDirty();
  39645. },
  39646. enumerable: true,
  39647. configurable: true
  39648. });
  39649. /**
  39650. * Return the active textures of the material.
  39651. */
  39652. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  39653. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39654. if (this.environmentTexture) {
  39655. activeTextures.push(this.environmentTexture);
  39656. }
  39657. if (this.normalTexture) {
  39658. activeTextures.push(this.normalTexture);
  39659. }
  39660. if (this.emissiveTexture) {
  39661. activeTextures.push(this.emissiveTexture);
  39662. }
  39663. if (this.occlusionTexture) {
  39664. activeTextures.push(this.occlusionTexture);
  39665. }
  39666. if (this.lightmapTexture) {
  39667. activeTextures.push(this.lightmapTexture);
  39668. }
  39669. return activeTextures;
  39670. };
  39671. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  39672. if (_super.prototype.hasTexture.call(this, texture)) {
  39673. return true;
  39674. }
  39675. if (this.lightmapTexture === texture) {
  39676. return true;
  39677. }
  39678. return false;
  39679. };
  39680. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  39681. return "PBRBaseSimpleMaterial";
  39682. };
  39683. __decorate([
  39684. BABYLON.serialize(),
  39685. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39686. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39687. __decorate([
  39688. BABYLON.serialize(),
  39689. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39690. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39691. __decorate([
  39692. BABYLON.serializeAsTexture(),
  39693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  39694. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39695. __decorate([
  39696. BABYLON.serialize(),
  39697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39698. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39699. __decorate([
  39700. BABYLON.serialize(),
  39701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39702. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39703. __decorate([
  39704. BABYLON.serializeAsTexture(),
  39705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  39706. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39707. __decorate([
  39708. BABYLON.serializeAsColor3("emissive"),
  39709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39710. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39711. __decorate([
  39712. BABYLON.serializeAsTexture(),
  39713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39714. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39715. __decorate([
  39716. BABYLON.serialize(),
  39717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  39718. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39719. __decorate([
  39720. BABYLON.serializeAsTexture(),
  39721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  39722. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39723. __decorate([
  39724. BABYLON.serialize(),
  39725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  39726. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39727. __decorate([
  39728. BABYLON.serialize()
  39729. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39730. __decorate([
  39731. BABYLON.serializeAsTexture(),
  39732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39733. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  39734. __decorate([
  39735. BABYLON.serialize(),
  39736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39737. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39738. return PBRBaseSimpleMaterial;
  39739. }(BABYLON.PBRBaseMaterial));
  39740. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39741. })(BABYLON || (BABYLON = {}));
  39742. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39743. var BABYLON;
  39744. (function (BABYLON) {
  39745. /**
  39746. * The Physically based material of BJS.
  39747. *
  39748. * This offers the main features of a standard PBR material.
  39749. * For more information, please refer to the documentation :
  39750. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39751. */
  39752. var PBRMaterial = /** @class */ (function (_super) {
  39753. __extends(PBRMaterial, _super);
  39754. /**
  39755. * Instantiates a new PBRMaterial instance.
  39756. *
  39757. * @param name The material name
  39758. * @param scene The scene the material will be use in.
  39759. */
  39760. function PBRMaterial(name, scene) {
  39761. var _this = _super.call(this, name, scene) || this;
  39762. /**
  39763. * Intensity of the direct lights e.g. the four lights available in your scene.
  39764. * This impacts both the direct diffuse and specular highlights.
  39765. */
  39766. _this.directIntensity = 1.0;
  39767. /**
  39768. * Intensity of the emissive part of the material.
  39769. * This helps controlling the emissive effect without modifying the emissive color.
  39770. */
  39771. _this.emissiveIntensity = 1.0;
  39772. /**
  39773. * Intensity of the environment e.g. how much the environment will light the object
  39774. * either through harmonics for rough material or through the refelction for shiny ones.
  39775. */
  39776. _this.environmentIntensity = 1.0;
  39777. /**
  39778. * This is a special control allowing the reduction of the specular highlights coming from the
  39779. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39780. */
  39781. _this.specularIntensity = 1.0;
  39782. /**
  39783. * Debug Control allowing disabling the bump map on this material.
  39784. */
  39785. _this.disableBumpMap = false;
  39786. /**
  39787. * AKA Occlusion Texture Intensity in other nomenclature.
  39788. */
  39789. _this.ambientTextureStrength = 1.0;
  39790. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39791. /**
  39792. * AKA Diffuse Color in other nomenclature.
  39793. */
  39794. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39795. /**
  39796. * AKA Specular Color in other nomenclature.
  39797. */
  39798. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39799. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  39800. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39801. /**
  39802. * AKA Glossiness in other nomenclature.
  39803. */
  39804. _this.microSurface = 1.0;
  39805. /**
  39806. * source material index of refraction (IOR)' / 'destination material IOR.
  39807. */
  39808. _this.indexOfRefraction = 0.66;
  39809. /**
  39810. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39811. */
  39812. _this.invertRefractionY = false;
  39813. /**
  39814. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39815. * Materials half opaque for instance using refraction could benefit from this control.
  39816. */
  39817. _this.linkRefractionWithTransparency = false;
  39818. _this.useLightmapAsShadowmap = false;
  39819. /**
  39820. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39821. */
  39822. _this.useAlphaFromAlbedoTexture = false;
  39823. /**
  39824. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39825. */
  39826. _this.forceAlphaTest = false;
  39827. /**
  39828. * Defines the alpha limits in alpha test mode.
  39829. */
  39830. _this.alphaCutOff = 0.4;
  39831. /**
  39832. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39833. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39834. */
  39835. _this.useSpecularOverAlpha = true;
  39836. /**
  39837. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39838. */
  39839. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39840. /**
  39841. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39842. */
  39843. _this.useRoughnessFromMetallicTextureAlpha = true;
  39844. /**
  39845. * Specifies if the metallic texture contains the roughness information in its green channel.
  39846. */
  39847. _this.useRoughnessFromMetallicTextureGreen = false;
  39848. /**
  39849. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39850. */
  39851. _this.useMetallnessFromMetallicTextureBlue = false;
  39852. /**
  39853. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39854. */
  39855. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39856. /**
  39857. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39858. */
  39859. _this.useAmbientInGrayScale = false;
  39860. /**
  39861. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39862. * The material will try to infer what glossiness each pixel should be.
  39863. */
  39864. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39865. /**
  39866. * BJS is using an harcoded light falloff based on a manually sets up range.
  39867. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39868. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39869. */
  39870. _this.usePhysicalLightFalloff = true;
  39871. /**
  39872. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39873. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39874. */
  39875. _this.useRadianceOverAlpha = true;
  39876. /**
  39877. * Allows using the bump map in parallax mode.
  39878. */
  39879. _this.useParallax = false;
  39880. /**
  39881. * Allows using the bump map in parallax occlusion mode.
  39882. */
  39883. _this.useParallaxOcclusion = false;
  39884. /**
  39885. * Controls the scale bias of the parallax mode.
  39886. */
  39887. _this.parallaxScaleBias = 0.05;
  39888. /**
  39889. * If sets to true, disables all the lights affecting the material.
  39890. */
  39891. _this.disableLighting = false;
  39892. /**
  39893. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39894. */
  39895. _this.forceIrradianceInFragment = false;
  39896. /**
  39897. * Number of Simultaneous lights allowed on the material.
  39898. */
  39899. _this.maxSimultaneousLights = 4;
  39900. /**
  39901. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39902. */
  39903. _this.invertNormalMapX = false;
  39904. /**
  39905. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39906. */
  39907. _this.invertNormalMapY = false;
  39908. /**
  39909. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39910. */
  39911. _this.twoSidedLighting = false;
  39912. /**
  39913. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39914. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39915. */
  39916. _this.useAlphaFresnel = false;
  39917. /**
  39918. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39919. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39920. */
  39921. _this.useLinearAlphaFresnel = false;
  39922. /**
  39923. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39924. * And/Or occlude the blended part.
  39925. */
  39926. _this.environmentBRDFTexture = null;
  39927. /**
  39928. * Force normal to face away from face.
  39929. */
  39930. _this.forceNormalForward = false;
  39931. /**
  39932. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39933. * makes the reflect vector face the model (under horizon).
  39934. */
  39935. _this.useHorizonOcclusion = true;
  39936. /**
  39937. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39938. * too much the area relying on ambient texture to define their ambient occlusion.
  39939. */
  39940. _this.useRadianceOcclusion = true;
  39941. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39942. return _this;
  39943. }
  39944. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39945. /**
  39946. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39947. */
  39948. get: function () {
  39949. return this._PBRMATERIAL_OPAQUE;
  39950. },
  39951. enumerable: true,
  39952. configurable: true
  39953. });
  39954. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39955. /**
  39956. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39957. */
  39958. get: function () {
  39959. return this._PBRMATERIAL_ALPHATEST;
  39960. },
  39961. enumerable: true,
  39962. configurable: true
  39963. });
  39964. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39965. /**
  39966. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39967. */
  39968. get: function () {
  39969. return this._PBRMATERIAL_ALPHABLEND;
  39970. },
  39971. enumerable: true,
  39972. configurable: true
  39973. });
  39974. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39975. /**
  39976. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39977. * They are also discarded below the alpha cutoff threshold to improve performances.
  39978. */
  39979. get: function () {
  39980. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39981. },
  39982. enumerable: true,
  39983. configurable: true
  39984. });
  39985. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  39986. /**
  39987. * Gets the image processing configuration used either in this material.
  39988. */
  39989. get: function () {
  39990. return this._imageProcessingConfiguration;
  39991. },
  39992. /**
  39993. * Sets the Default image processing configuration used either in the this material.
  39994. *
  39995. * If sets to null, the scene one is in use.
  39996. */
  39997. set: function (value) {
  39998. this._attachImageProcessingConfiguration(value);
  39999. // Ensure the effect will be rebuilt.
  40000. this._markAllSubMeshesAsTexturesDirty();
  40001. },
  40002. enumerable: true,
  40003. configurable: true
  40004. });
  40005. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  40006. /**
  40007. * Gets wether the color curves effect is enabled.
  40008. */
  40009. get: function () {
  40010. return this.imageProcessingConfiguration.colorCurvesEnabled;
  40011. },
  40012. /**
  40013. * Sets wether the color curves effect is enabled.
  40014. */
  40015. set: function (value) {
  40016. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  40017. },
  40018. enumerable: true,
  40019. configurable: true
  40020. });
  40021. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  40022. /**
  40023. * Gets wether the color grading effect is enabled.
  40024. */
  40025. get: function () {
  40026. return this.imageProcessingConfiguration.colorGradingEnabled;
  40027. },
  40028. /**
  40029. * Gets wether the color grading effect is enabled.
  40030. */
  40031. set: function (value) {
  40032. this.imageProcessingConfiguration.colorGradingEnabled = value;
  40033. },
  40034. enumerable: true,
  40035. configurable: true
  40036. });
  40037. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  40038. /**
  40039. * Gets wether tonemapping is enabled or not.
  40040. */
  40041. get: function () {
  40042. return this._imageProcessingConfiguration.toneMappingEnabled;
  40043. },
  40044. /**
  40045. * Sets wether tonemapping is enabled or not
  40046. */
  40047. set: function (value) {
  40048. this._imageProcessingConfiguration.toneMappingEnabled = value;
  40049. },
  40050. enumerable: true,
  40051. configurable: true
  40052. });
  40053. ;
  40054. ;
  40055. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  40056. /**
  40057. * The camera exposure used on this material.
  40058. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  40059. * This corresponds to a photographic exposure.
  40060. */
  40061. get: function () {
  40062. return this._imageProcessingConfiguration.exposure;
  40063. },
  40064. /**
  40065. * The camera exposure used on this material.
  40066. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  40067. * This corresponds to a photographic exposure.
  40068. */
  40069. set: function (value) {
  40070. this._imageProcessingConfiguration.exposure = value;
  40071. },
  40072. enumerable: true,
  40073. configurable: true
  40074. });
  40075. ;
  40076. ;
  40077. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  40078. /**
  40079. * Gets The camera contrast used on this material.
  40080. */
  40081. get: function () {
  40082. return this._imageProcessingConfiguration.contrast;
  40083. },
  40084. /**
  40085. * Sets The camera contrast used on this material.
  40086. */
  40087. set: function (value) {
  40088. this._imageProcessingConfiguration.contrast = value;
  40089. },
  40090. enumerable: true,
  40091. configurable: true
  40092. });
  40093. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  40094. /**
  40095. * Gets the Color Grading 2D Lookup Texture.
  40096. */
  40097. get: function () {
  40098. return this._imageProcessingConfiguration.colorGradingTexture;
  40099. },
  40100. /**
  40101. * Sets the Color Grading 2D Lookup Texture.
  40102. */
  40103. set: function (value) {
  40104. this._imageProcessingConfiguration.colorGradingTexture = value;
  40105. },
  40106. enumerable: true,
  40107. configurable: true
  40108. });
  40109. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  40110. /**
  40111. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40112. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40113. * 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;
  40114. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40115. */
  40116. get: function () {
  40117. return this._imageProcessingConfiguration.colorCurves;
  40118. },
  40119. /**
  40120. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40121. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40122. * 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;
  40123. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40124. */
  40125. set: function (value) {
  40126. this._imageProcessingConfiguration.colorCurves = value;
  40127. },
  40128. enumerable: true,
  40129. configurable: true
  40130. });
  40131. PBRMaterial.prototype.getClassName = function () {
  40132. return "PBRMaterial";
  40133. };
  40134. PBRMaterial.prototype.getActiveTextures = function () {
  40135. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40136. if (this._albedoTexture) {
  40137. activeTextures.push(this._albedoTexture);
  40138. }
  40139. if (this._ambientTexture) {
  40140. activeTextures.push(this._ambientTexture);
  40141. }
  40142. if (this._opacityTexture) {
  40143. activeTextures.push(this._opacityTexture);
  40144. }
  40145. if (this._reflectionTexture) {
  40146. activeTextures.push(this._reflectionTexture);
  40147. }
  40148. if (this._emissiveTexture) {
  40149. activeTextures.push(this._emissiveTexture);
  40150. }
  40151. if (this._reflectivityTexture) {
  40152. activeTextures.push(this._reflectivityTexture);
  40153. }
  40154. if (this._metallicTexture) {
  40155. activeTextures.push(this._metallicTexture);
  40156. }
  40157. if (this._microSurfaceTexture) {
  40158. activeTextures.push(this._microSurfaceTexture);
  40159. }
  40160. if (this._bumpTexture) {
  40161. activeTextures.push(this._bumpTexture);
  40162. }
  40163. if (this._lightmapTexture) {
  40164. activeTextures.push(this._lightmapTexture);
  40165. }
  40166. if (this._refractionTexture) {
  40167. activeTextures.push(this._refractionTexture);
  40168. }
  40169. return activeTextures;
  40170. };
  40171. PBRMaterial.prototype.hasTexture = function (texture) {
  40172. if (_super.prototype.hasTexture.call(this, texture)) {
  40173. return true;
  40174. }
  40175. if (this._albedoTexture === texture) {
  40176. return true;
  40177. }
  40178. if (this._ambientTexture === texture) {
  40179. return true;
  40180. }
  40181. if (this._opacityTexture === texture) {
  40182. return true;
  40183. }
  40184. if (this._reflectionTexture === texture) {
  40185. return true;
  40186. }
  40187. if (this._reflectivityTexture === texture) {
  40188. return true;
  40189. }
  40190. if (this._metallicTexture === texture) {
  40191. return true;
  40192. }
  40193. if (this._microSurfaceTexture === texture) {
  40194. return true;
  40195. }
  40196. if (this._bumpTexture === texture) {
  40197. return true;
  40198. }
  40199. if (this._lightmapTexture === texture) {
  40200. return true;
  40201. }
  40202. if (this._refractionTexture === texture) {
  40203. return true;
  40204. }
  40205. return false;
  40206. };
  40207. PBRMaterial.prototype.clone = function (name) {
  40208. var _this = this;
  40209. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  40210. clone.id = name;
  40211. clone.name = name;
  40212. return clone;
  40213. };
  40214. PBRMaterial.prototype.serialize = function () {
  40215. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40216. serializationObject.customType = "BABYLON.PBRMaterial";
  40217. return serializationObject;
  40218. };
  40219. // Statics
  40220. PBRMaterial.Parse = function (source, scene, rootUrl) {
  40221. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  40222. };
  40223. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  40224. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  40225. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  40226. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  40227. __decorate([
  40228. BABYLON.serialize(),
  40229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40230. ], PBRMaterial.prototype, "directIntensity", void 0);
  40231. __decorate([
  40232. BABYLON.serialize(),
  40233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40234. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  40235. __decorate([
  40236. BABYLON.serialize(),
  40237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40238. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  40239. __decorate([
  40240. BABYLON.serialize(),
  40241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40242. ], PBRMaterial.prototype, "specularIntensity", void 0);
  40243. __decorate([
  40244. BABYLON.serialize(),
  40245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40246. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  40247. __decorate([
  40248. BABYLON.serializeAsTexture(),
  40249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40250. ], PBRMaterial.prototype, "albedoTexture", void 0);
  40251. __decorate([
  40252. BABYLON.serializeAsTexture(),
  40253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40254. ], PBRMaterial.prototype, "ambientTexture", void 0);
  40255. __decorate([
  40256. BABYLON.serialize(),
  40257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40258. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  40259. __decorate([
  40260. BABYLON.serializeAsTexture(),
  40261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40262. ], PBRMaterial.prototype, "opacityTexture", void 0);
  40263. __decorate([
  40264. BABYLON.serializeAsTexture(),
  40265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40266. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  40267. __decorate([
  40268. BABYLON.serializeAsTexture(),
  40269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40270. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  40271. __decorate([
  40272. BABYLON.serializeAsTexture(),
  40273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40274. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  40275. __decorate([
  40276. BABYLON.serializeAsTexture(),
  40277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40278. ], PBRMaterial.prototype, "metallicTexture", void 0);
  40279. __decorate([
  40280. BABYLON.serialize(),
  40281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40282. ], PBRMaterial.prototype, "metallic", void 0);
  40283. __decorate([
  40284. BABYLON.serialize(),
  40285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40286. ], PBRMaterial.prototype, "roughness", void 0);
  40287. __decorate([
  40288. BABYLON.serializeAsTexture(),
  40289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40290. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  40291. __decorate([
  40292. BABYLON.serializeAsTexture(),
  40293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40294. ], PBRMaterial.prototype, "bumpTexture", void 0);
  40295. __decorate([
  40296. BABYLON.serializeAsTexture(),
  40297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  40298. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  40299. __decorate([
  40300. BABYLON.serializeAsTexture(),
  40301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40302. ], PBRMaterial.prototype, "refractionTexture", void 0);
  40303. __decorate([
  40304. BABYLON.serializeAsColor3("ambient"),
  40305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40306. ], PBRMaterial.prototype, "ambientColor", void 0);
  40307. __decorate([
  40308. BABYLON.serializeAsColor3("albedo"),
  40309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40310. ], PBRMaterial.prototype, "albedoColor", void 0);
  40311. __decorate([
  40312. BABYLON.serializeAsColor3("reflectivity"),
  40313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40314. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  40315. __decorate([
  40316. BABYLON.serializeAsColor3("reflection"),
  40317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40318. ], PBRMaterial.prototype, "reflectionColor", void 0);
  40319. __decorate([
  40320. BABYLON.serializeAsColor3("emissive"),
  40321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40322. ], PBRMaterial.prototype, "emissiveColor", void 0);
  40323. __decorate([
  40324. BABYLON.serialize(),
  40325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40326. ], PBRMaterial.prototype, "microSurface", void 0);
  40327. __decorate([
  40328. BABYLON.serialize(),
  40329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40330. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  40331. __decorate([
  40332. BABYLON.serialize(),
  40333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40334. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  40335. __decorate([
  40336. BABYLON.serialize(),
  40337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40338. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  40339. __decorate([
  40340. BABYLON.serialize(),
  40341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40342. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40343. __decorate([
  40344. BABYLON.serialize(),
  40345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40346. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  40347. __decorate([
  40348. BABYLON.serialize(),
  40349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40350. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  40351. __decorate([
  40352. BABYLON.serialize(),
  40353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40354. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  40355. __decorate([
  40356. BABYLON.serialize(),
  40357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40358. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  40359. __decorate([
  40360. BABYLON.serialize(),
  40361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40362. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  40363. __decorate([
  40364. BABYLON.serialize(),
  40365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40366. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  40367. __decorate([
  40368. BABYLON.serialize(),
  40369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40370. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  40371. __decorate([
  40372. BABYLON.serialize(),
  40373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40374. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  40375. __decorate([
  40376. BABYLON.serialize(),
  40377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40378. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  40379. __decorate([
  40380. BABYLON.serialize(),
  40381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40382. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  40383. __decorate([
  40384. BABYLON.serialize(),
  40385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40386. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  40387. __decorate([
  40388. BABYLON.serialize(),
  40389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40390. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  40391. __decorate([
  40392. BABYLON.serialize(),
  40393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40394. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  40395. __decorate([
  40396. BABYLON.serialize(),
  40397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40398. ], PBRMaterial.prototype, "useParallax", void 0);
  40399. __decorate([
  40400. BABYLON.serialize(),
  40401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40402. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  40403. __decorate([
  40404. BABYLON.serialize(),
  40405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40406. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  40407. __decorate([
  40408. BABYLON.serialize(),
  40409. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40410. ], PBRMaterial.prototype, "disableLighting", void 0);
  40411. __decorate([
  40412. BABYLON.serialize(),
  40413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40414. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  40415. __decorate([
  40416. BABYLON.serialize(),
  40417. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40418. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  40419. __decorate([
  40420. BABYLON.serialize(),
  40421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40422. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  40423. __decorate([
  40424. BABYLON.serialize(),
  40425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40426. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  40427. __decorate([
  40428. BABYLON.serialize(),
  40429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40430. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  40431. __decorate([
  40432. BABYLON.serialize(),
  40433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40434. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  40435. __decorate([
  40436. BABYLON.serialize(),
  40437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40438. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  40439. __decorate([
  40440. BABYLON.serializeAsTexture(),
  40441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40442. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  40443. __decorate([
  40444. BABYLON.serialize(),
  40445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40446. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  40447. __decorate([
  40448. BABYLON.serialize(),
  40449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40450. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  40451. __decorate([
  40452. BABYLON.serialize(),
  40453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40454. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  40455. return PBRMaterial;
  40456. }(BABYLON.PBRBaseMaterial));
  40457. BABYLON.PBRMaterial = PBRMaterial;
  40458. })(BABYLON || (BABYLON = {}));
  40459. //# sourceMappingURL=babylon.pbrMaterial.js.map
  40460. var BABYLON;
  40461. (function (BABYLON) {
  40462. /**
  40463. * The PBR material of BJS following the metal roughness convention.
  40464. *
  40465. * This fits to the PBR convention in the GLTF definition:
  40466. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  40467. */
  40468. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  40469. __extends(PBRMetallicRoughnessMaterial, _super);
  40470. /**
  40471. * Instantiates a new PBRMetalRoughnessMaterial instance.
  40472. *
  40473. * @param name The material name
  40474. * @param scene The scene the material will be use in.
  40475. */
  40476. function PBRMetallicRoughnessMaterial(name, scene) {
  40477. var _this = _super.call(this, name, scene) || this;
  40478. _this._useRoughnessFromMetallicTextureAlpha = false;
  40479. _this._useRoughnessFromMetallicTextureGreen = true;
  40480. _this._useMetallnessFromMetallicTextureBlue = true;
  40481. _this._forceMetallicWorkflow = true;
  40482. return _this;
  40483. }
  40484. /**
  40485. * Return the currrent class name of the material.
  40486. */
  40487. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  40488. return "PBRMetallicRoughnessMaterial";
  40489. };
  40490. /**
  40491. * Return the active textures of the material.
  40492. */
  40493. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  40494. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40495. if (this.baseTexture) {
  40496. activeTextures.push(this.baseTexture);
  40497. }
  40498. if (this.metallicRoughnessTexture) {
  40499. activeTextures.push(this.metallicRoughnessTexture);
  40500. }
  40501. return activeTextures;
  40502. };
  40503. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  40504. if (_super.prototype.hasTexture.call(this, texture)) {
  40505. return true;
  40506. }
  40507. if (this.baseTexture === texture) {
  40508. return true;
  40509. }
  40510. if (this.metallicRoughnessTexture === texture) {
  40511. return true;
  40512. }
  40513. return false;
  40514. };
  40515. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  40516. var _this = this;
  40517. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  40518. clone.id = name;
  40519. clone.name = name;
  40520. return clone;
  40521. };
  40522. /**
  40523. * Serialize the material to a parsable JSON object.
  40524. */
  40525. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  40526. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40527. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  40528. return serializationObject;
  40529. };
  40530. /**
  40531. * Parses a JSON object correponding to the serialize function.
  40532. */
  40533. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  40534. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  40535. };
  40536. __decorate([
  40537. BABYLON.serializeAsColor3(),
  40538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40539. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  40540. __decorate([
  40541. BABYLON.serializeAsTexture(),
  40542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40543. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  40544. __decorate([
  40545. BABYLON.serialize(),
  40546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40547. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  40548. __decorate([
  40549. BABYLON.serialize(),
  40550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40551. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  40552. __decorate([
  40553. BABYLON.serializeAsTexture(),
  40554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  40555. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  40556. return PBRMetallicRoughnessMaterial;
  40557. }(BABYLON.PBRBaseSimpleMaterial));
  40558. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  40559. })(BABYLON || (BABYLON = {}));
  40560. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  40561. var BABYLON;
  40562. (function (BABYLON) {
  40563. /**
  40564. * The PBR material of BJS following the specular glossiness convention.
  40565. *
  40566. * This fits to the PBR convention in the GLTF definition:
  40567. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  40568. */
  40569. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  40570. __extends(PBRSpecularGlossinessMaterial, _super);
  40571. /**
  40572. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  40573. *
  40574. * @param name The material name
  40575. * @param scene The scene the material will be use in.
  40576. */
  40577. function PBRSpecularGlossinessMaterial(name, scene) {
  40578. var _this = _super.call(this, name, scene) || this;
  40579. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  40580. return _this;
  40581. }
  40582. /**
  40583. * Return the currrent class name of the material.
  40584. */
  40585. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  40586. return "PBRSpecularGlossinessMaterial";
  40587. };
  40588. /**
  40589. * Return the active textures of the material.
  40590. */
  40591. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  40592. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40593. if (this.diffuseTexture) {
  40594. activeTextures.push(this.diffuseTexture);
  40595. }
  40596. if (this.specularGlossinessTexture) {
  40597. activeTextures.push(this.specularGlossinessTexture);
  40598. }
  40599. return activeTextures;
  40600. };
  40601. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  40602. if (_super.prototype.hasTexture.call(this, texture)) {
  40603. return true;
  40604. }
  40605. if (this.diffuseTexture === texture) {
  40606. return true;
  40607. }
  40608. if (this.specularGlossinessTexture === texture) {
  40609. return true;
  40610. }
  40611. return false;
  40612. };
  40613. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  40614. var _this = this;
  40615. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  40616. clone.id = name;
  40617. clone.name = name;
  40618. return clone;
  40619. };
  40620. /**
  40621. * Serialize the material to a parsable JSON object.
  40622. */
  40623. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  40624. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40625. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  40626. return serializationObject;
  40627. };
  40628. /**
  40629. * Parses a JSON object correponding to the serialize function.
  40630. */
  40631. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  40632. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  40633. };
  40634. __decorate([
  40635. BABYLON.serializeAsColor3("diffuse"),
  40636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40637. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  40638. __decorate([
  40639. BABYLON.serializeAsTexture(),
  40640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40641. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  40642. __decorate([
  40643. BABYLON.serializeAsColor3("specular"),
  40644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  40645. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  40646. __decorate([
  40647. BABYLON.serialize(),
  40648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  40649. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  40650. __decorate([
  40651. BABYLON.serializeAsTexture(),
  40652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  40653. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  40654. return PBRSpecularGlossinessMaterial;
  40655. }(BABYLON.PBRBaseSimpleMaterial));
  40656. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  40657. })(BABYLON || (BABYLON = {}));
  40658. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40659. var BABYLON;
  40660. (function (BABYLON) {
  40661. BABYLON.CameraInputTypes = {};
  40662. var CameraInputsManager = /** @class */ (function () {
  40663. function CameraInputsManager(camera) {
  40664. this.attached = {};
  40665. this.camera = camera;
  40666. this.checkInputs = function () { };
  40667. }
  40668. /**
  40669. * Add an input method to a camera.
  40670. * builtin inputs example: camera.inputs.addGamepad();
  40671. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  40672. * @param input camera input method
  40673. */
  40674. CameraInputsManager.prototype.add = function (input) {
  40675. var type = input.getSimpleName();
  40676. if (this.attached[type]) {
  40677. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  40678. return;
  40679. }
  40680. this.attached[type] = input;
  40681. input.camera = this.camera;
  40682. //for checkInputs, we are dynamically creating a function
  40683. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  40684. if (input.checkInputs) {
  40685. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40686. }
  40687. if (this.attachedElement) {
  40688. input.attachControl(this.attachedElement);
  40689. }
  40690. };
  40691. /**
  40692. * Remove a specific input method from a camera
  40693. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  40694. * @param inputToRemove camera input method
  40695. */
  40696. CameraInputsManager.prototype.remove = function (inputToRemove) {
  40697. for (var cam in this.attached) {
  40698. var input = this.attached[cam];
  40699. if (input === inputToRemove) {
  40700. input.detachControl(this.attachedElement);
  40701. input.camera = null;
  40702. delete this.attached[cam];
  40703. this.rebuildInputCheck();
  40704. }
  40705. }
  40706. };
  40707. CameraInputsManager.prototype.removeByType = function (inputType) {
  40708. for (var cam in this.attached) {
  40709. var input = this.attached[cam];
  40710. if (input.getClassName() === inputType) {
  40711. input.detachControl(this.attachedElement);
  40712. input.camera = null;
  40713. delete this.attached[cam];
  40714. this.rebuildInputCheck();
  40715. }
  40716. }
  40717. };
  40718. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  40719. var current = this.checkInputs;
  40720. return function () {
  40721. current();
  40722. fn();
  40723. };
  40724. };
  40725. CameraInputsManager.prototype.attachInput = function (input) {
  40726. if (this.attachedElement) {
  40727. input.attachControl(this.attachedElement, this.noPreventDefault);
  40728. }
  40729. };
  40730. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  40731. if (noPreventDefault === void 0) { noPreventDefault = false; }
  40732. if (this.attachedElement) {
  40733. return;
  40734. }
  40735. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  40736. this.attachedElement = element;
  40737. this.noPreventDefault = noPreventDefault;
  40738. for (var cam in this.attached) {
  40739. this.attached[cam].attachControl(element, noPreventDefault);
  40740. }
  40741. };
  40742. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  40743. if (disconnect === void 0) { disconnect = false; }
  40744. if (this.attachedElement !== element) {
  40745. return;
  40746. }
  40747. for (var cam in this.attached) {
  40748. this.attached[cam].detachControl(element);
  40749. if (disconnect) {
  40750. this.attached[cam].camera = null;
  40751. }
  40752. }
  40753. this.attachedElement = null;
  40754. };
  40755. CameraInputsManager.prototype.rebuildInputCheck = function () {
  40756. this.checkInputs = function () { };
  40757. for (var cam in this.attached) {
  40758. var input = this.attached[cam];
  40759. if (input.checkInputs) {
  40760. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40761. }
  40762. }
  40763. };
  40764. /**
  40765. * Remove all attached input methods from a camera
  40766. */
  40767. CameraInputsManager.prototype.clear = function () {
  40768. if (this.attachedElement) {
  40769. this.detachElement(this.attachedElement, true);
  40770. }
  40771. this.attached = {};
  40772. this.attachedElement = null;
  40773. this.checkInputs = function () { };
  40774. };
  40775. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  40776. var inputs = {};
  40777. for (var cam in this.attached) {
  40778. var input = this.attached[cam];
  40779. var res = BABYLON.SerializationHelper.Serialize(input);
  40780. inputs[input.getClassName()] = res;
  40781. }
  40782. serializedCamera.inputsmgr = inputs;
  40783. };
  40784. CameraInputsManager.prototype.parse = function (parsedCamera) {
  40785. var parsedInputs = parsedCamera.inputsmgr;
  40786. if (parsedInputs) {
  40787. this.clear();
  40788. for (var n in parsedInputs) {
  40789. var construct = BABYLON.CameraInputTypes[n];
  40790. if (construct) {
  40791. var parsedinput = parsedInputs[n];
  40792. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  40793. this.add(input);
  40794. }
  40795. }
  40796. }
  40797. else {
  40798. //2016-03-08 this part is for managing backward compatibility
  40799. for (var n in this.attached) {
  40800. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  40801. if (construct) {
  40802. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  40803. this.remove(this.attached[n]);
  40804. this.add(input);
  40805. }
  40806. }
  40807. }
  40808. };
  40809. return CameraInputsManager;
  40810. }());
  40811. BABYLON.CameraInputsManager = CameraInputsManager;
  40812. })(BABYLON || (BABYLON = {}));
  40813. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  40814. var BABYLON;
  40815. (function (BABYLON) {
  40816. var TargetCamera = /** @class */ (function (_super) {
  40817. __extends(TargetCamera, _super);
  40818. function TargetCamera(name, position, scene) {
  40819. var _this = _super.call(this, name, position, scene) || this;
  40820. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40821. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  40822. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  40823. _this.speed = 2.0;
  40824. _this.noRotationConstraint = false;
  40825. _this.lockedTarget = null;
  40826. _this._currentTarget = BABYLON.Vector3.Zero();
  40827. _this._viewMatrix = BABYLON.Matrix.Zero();
  40828. _this._camMatrix = BABYLON.Matrix.Zero();
  40829. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  40830. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  40831. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  40832. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  40833. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  40834. _this._lookAtTemp = BABYLON.Matrix.Zero();
  40835. _this._tempMatrix = BABYLON.Matrix.Zero();
  40836. return _this;
  40837. }
  40838. TargetCamera.prototype.getFrontPosition = function (distance) {
  40839. this.getWorldMatrix();
  40840. var direction = this.getTarget().subtract(this.position);
  40841. direction.normalize();
  40842. direction.scaleInPlace(distance);
  40843. return this.globalPosition.add(direction);
  40844. };
  40845. TargetCamera.prototype._getLockedTargetPosition = function () {
  40846. if (!this.lockedTarget) {
  40847. return null;
  40848. }
  40849. if (this.lockedTarget.absolutePosition) {
  40850. this.lockedTarget.computeWorldMatrix();
  40851. }
  40852. return this.lockedTarget.absolutePosition || this.lockedTarget;
  40853. };
  40854. TargetCamera.prototype.storeState = function () {
  40855. this._storedPosition = this.position.clone();
  40856. this._storedRotation = this.rotation.clone();
  40857. if (this.rotationQuaternion) {
  40858. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  40859. }
  40860. return _super.prototype.storeState.call(this);
  40861. };
  40862. /**
  40863. * Restored camera state. You must call storeState() first
  40864. */
  40865. TargetCamera.prototype._restoreStateValues = function () {
  40866. if (!_super.prototype._restoreStateValues.call(this)) {
  40867. return false;
  40868. }
  40869. this.position = this._storedPosition.clone();
  40870. this.rotation = this._storedRotation.clone();
  40871. if (this.rotationQuaternion) {
  40872. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  40873. }
  40874. this.cameraDirection.copyFromFloats(0, 0, 0);
  40875. this.cameraRotation.copyFromFloats(0, 0);
  40876. return true;
  40877. };
  40878. // Cache
  40879. TargetCamera.prototype._initCache = function () {
  40880. _super.prototype._initCache.call(this);
  40881. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40882. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40883. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40884. };
  40885. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  40886. if (!ignoreParentClass) {
  40887. _super.prototype._updateCache.call(this);
  40888. }
  40889. var lockedTargetPosition = this._getLockedTargetPosition();
  40890. if (!lockedTargetPosition) {
  40891. this._cache.lockedTarget = null;
  40892. }
  40893. else {
  40894. if (!this._cache.lockedTarget) {
  40895. this._cache.lockedTarget = lockedTargetPosition.clone();
  40896. }
  40897. else {
  40898. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  40899. }
  40900. }
  40901. this._cache.rotation.copyFrom(this.rotation);
  40902. if (this.rotationQuaternion)
  40903. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40904. };
  40905. // Synchronized
  40906. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  40907. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  40908. return false;
  40909. }
  40910. var lockedTargetPosition = this._getLockedTargetPosition();
  40911. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  40912. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  40913. };
  40914. // Methods
  40915. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  40916. var engine = this.getEngine();
  40917. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  40918. };
  40919. // Target
  40920. TargetCamera.prototype.setTarget = function (target) {
  40921. this.upVector.normalize();
  40922. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  40923. this._camMatrix.invert();
  40924. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  40925. var vDir = target.subtract(this.position);
  40926. if (vDir.x >= 0.0) {
  40927. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  40928. }
  40929. else {
  40930. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  40931. }
  40932. this.rotation.z = 0;
  40933. if (isNaN(this.rotation.x)) {
  40934. this.rotation.x = 0;
  40935. }
  40936. if (isNaN(this.rotation.y)) {
  40937. this.rotation.y = 0;
  40938. }
  40939. if (isNaN(this.rotation.z)) {
  40940. this.rotation.z = 0;
  40941. }
  40942. if (this.rotationQuaternion) {
  40943. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40944. }
  40945. };
  40946. /**
  40947. * Return the current target position of the camera. This value is expressed in local space.
  40948. */
  40949. TargetCamera.prototype.getTarget = function () {
  40950. return this._currentTarget;
  40951. };
  40952. TargetCamera.prototype._decideIfNeedsToMove = function () {
  40953. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40954. };
  40955. TargetCamera.prototype._updatePosition = function () {
  40956. if (this.parent) {
  40957. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40958. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40959. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40960. return;
  40961. }
  40962. this.position.addInPlace(this.cameraDirection);
  40963. };
  40964. TargetCamera.prototype._checkInputs = function () {
  40965. var needToMove = this._decideIfNeedsToMove();
  40966. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40967. // Move
  40968. if (needToMove) {
  40969. this._updatePosition();
  40970. }
  40971. // Rotate
  40972. if (needToRotate) {
  40973. this.rotation.x += this.cameraRotation.x;
  40974. this.rotation.y += this.cameraRotation.y;
  40975. //rotate, if quaternion is set and rotation was used
  40976. if (this.rotationQuaternion) {
  40977. var len = this.rotation.lengthSquared();
  40978. if (len) {
  40979. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40980. }
  40981. }
  40982. if (!this.noRotationConstraint) {
  40983. var limit = (Math.PI / 2) * 0.95;
  40984. if (this.rotation.x > limit)
  40985. this.rotation.x = limit;
  40986. if (this.rotation.x < -limit)
  40987. this.rotation.x = -limit;
  40988. }
  40989. }
  40990. // Inertia
  40991. if (needToMove) {
  40992. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  40993. this.cameraDirection.x = 0;
  40994. }
  40995. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  40996. this.cameraDirection.y = 0;
  40997. }
  40998. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  40999. this.cameraDirection.z = 0;
  41000. }
  41001. this.cameraDirection.scaleInPlace(this.inertia);
  41002. }
  41003. if (needToRotate) {
  41004. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  41005. this.cameraRotation.x = 0;
  41006. }
  41007. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  41008. this.cameraRotation.y = 0;
  41009. }
  41010. this.cameraRotation.scaleInPlace(this.inertia);
  41011. }
  41012. _super.prototype._checkInputs.call(this);
  41013. };
  41014. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  41015. if (this.rotationQuaternion) {
  41016. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  41017. }
  41018. else {
  41019. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  41020. }
  41021. //update the up vector!
  41022. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  41023. };
  41024. TargetCamera.prototype._getViewMatrix = function () {
  41025. if (this.lockedTarget) {
  41026. this.setTarget(this._getLockedTargetPosition());
  41027. }
  41028. // Compute
  41029. this._updateCameraRotationMatrix();
  41030. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  41031. // Computing target and final matrix
  41032. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  41033. if (this.getScene().useRightHandedSystem) {
  41034. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  41035. }
  41036. else {
  41037. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  41038. }
  41039. return this._viewMatrix;
  41040. };
  41041. /**
  41042. * @override
  41043. * Override Camera.createRigCamera
  41044. */
  41045. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  41046. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  41047. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  41048. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  41049. if (!this.rotationQuaternion) {
  41050. this.rotationQuaternion = new BABYLON.Quaternion();
  41051. }
  41052. rigCamera._cameraRigParams = {};
  41053. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  41054. }
  41055. return rigCamera;
  41056. }
  41057. return null;
  41058. };
  41059. /**
  41060. * @override
  41061. * Override Camera._updateRigCameras
  41062. */
  41063. TargetCamera.prototype._updateRigCameras = function () {
  41064. var camLeft = this._rigCameras[0];
  41065. var camRight = this._rigCameras[1];
  41066. switch (this.cameraRigMode) {
  41067. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  41068. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  41069. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  41070. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  41071. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  41072. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  41073. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  41074. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  41075. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  41076. camLeft.setTarget(this.getTarget());
  41077. camRight.setTarget(this.getTarget());
  41078. break;
  41079. case BABYLON.Camera.RIG_MODE_VR:
  41080. if (camLeft.rotationQuaternion) {
  41081. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  41082. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  41083. }
  41084. else {
  41085. camLeft.rotation.copyFrom(this.rotation);
  41086. camRight.rotation.copyFrom(this.rotation);
  41087. }
  41088. camLeft.position.copyFrom(this.position);
  41089. camRight.position.copyFrom(this.position);
  41090. break;
  41091. }
  41092. _super.prototype._updateRigCameras.call(this);
  41093. };
  41094. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  41095. if (!this._rigCamTransformMatrix) {
  41096. this._rigCamTransformMatrix = new BABYLON.Matrix();
  41097. }
  41098. var target = this.getTarget();
  41099. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  41100. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  41101. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  41102. };
  41103. TargetCamera.prototype.getClassName = function () {
  41104. return "TargetCamera";
  41105. };
  41106. __decorate([
  41107. BABYLON.serializeAsVector3()
  41108. ], TargetCamera.prototype, "rotation", void 0);
  41109. __decorate([
  41110. BABYLON.serialize()
  41111. ], TargetCamera.prototype, "speed", void 0);
  41112. __decorate([
  41113. BABYLON.serializeAsMeshReference("lockedTargetId")
  41114. ], TargetCamera.prototype, "lockedTarget", void 0);
  41115. return TargetCamera;
  41116. }(BABYLON.Camera));
  41117. BABYLON.TargetCamera = TargetCamera;
  41118. })(BABYLON || (BABYLON = {}));
  41119. //# sourceMappingURL=babylon.targetCamera.js.map
  41120. var BABYLON;
  41121. (function (BABYLON) {
  41122. var FreeCameraMouseInput = /** @class */ (function () {
  41123. function FreeCameraMouseInput(touchEnabled) {
  41124. if (touchEnabled === void 0) { touchEnabled = true; }
  41125. this.touchEnabled = touchEnabled;
  41126. this.buttons = [0, 1, 2];
  41127. this.angularSensibility = 2000.0;
  41128. this.previousPosition = null;
  41129. }
  41130. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  41131. var _this = this;
  41132. var engine = this.camera.getEngine();
  41133. if (!this._pointerInput) {
  41134. this._pointerInput = function (p, s) {
  41135. var evt = p.event;
  41136. if (engine.isInVRExclusivePointerMode) {
  41137. return;
  41138. }
  41139. if (!_this.touchEnabled && evt.pointerType === "touch") {
  41140. return;
  41141. }
  41142. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41143. return;
  41144. }
  41145. var srcElement = (evt.srcElement || evt.target);
  41146. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41147. try {
  41148. srcElement.setPointerCapture(evt.pointerId);
  41149. }
  41150. catch (e) {
  41151. //Nothing to do with the error. Execution will continue.
  41152. }
  41153. _this.previousPosition = {
  41154. x: evt.clientX,
  41155. y: evt.clientY
  41156. };
  41157. if (!noPreventDefault) {
  41158. evt.preventDefault();
  41159. element.focus();
  41160. }
  41161. }
  41162. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41163. try {
  41164. srcElement.releasePointerCapture(evt.pointerId);
  41165. }
  41166. catch (e) {
  41167. //Nothing to do with the error.
  41168. }
  41169. _this.previousPosition = null;
  41170. if (!noPreventDefault) {
  41171. evt.preventDefault();
  41172. }
  41173. }
  41174. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41175. if (!_this.previousPosition || engine.isPointerLock) {
  41176. return;
  41177. }
  41178. var offsetX = evt.clientX - _this.previousPosition.x;
  41179. var offsetY = evt.clientY - _this.previousPosition.y;
  41180. if (_this.camera.getScene().useRightHandedSystem) {
  41181. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41182. }
  41183. else {
  41184. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41185. }
  41186. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41187. _this.previousPosition = {
  41188. x: evt.clientX,
  41189. y: evt.clientY
  41190. };
  41191. if (!noPreventDefault) {
  41192. evt.preventDefault();
  41193. }
  41194. }
  41195. };
  41196. }
  41197. this._onMouseMove = function (evt) {
  41198. if (!engine.isPointerLock) {
  41199. return;
  41200. }
  41201. if (engine.isInVRExclusivePointerMode) {
  41202. return;
  41203. }
  41204. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41205. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41206. if (_this.camera.getScene().useRightHandedSystem) {
  41207. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41208. }
  41209. else {
  41210. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41211. }
  41212. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41213. _this.previousPosition = null;
  41214. if (!noPreventDefault) {
  41215. evt.preventDefault();
  41216. }
  41217. };
  41218. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  41219. element.addEventListener("mousemove", this._onMouseMove, false);
  41220. };
  41221. FreeCameraMouseInput.prototype.detachControl = function (element) {
  41222. if (this._observer && element) {
  41223. this.camera.getScene().onPointerObservable.remove(this._observer);
  41224. if (this._onMouseMove) {
  41225. element.removeEventListener("mousemove", this._onMouseMove);
  41226. }
  41227. this._observer = null;
  41228. this._onMouseMove = null;
  41229. this.previousPosition = null;
  41230. }
  41231. };
  41232. FreeCameraMouseInput.prototype.getClassName = function () {
  41233. return "FreeCameraMouseInput";
  41234. };
  41235. FreeCameraMouseInput.prototype.getSimpleName = function () {
  41236. return "mouse";
  41237. };
  41238. __decorate([
  41239. BABYLON.serialize()
  41240. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  41241. __decorate([
  41242. BABYLON.serialize()
  41243. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  41244. return FreeCameraMouseInput;
  41245. }());
  41246. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  41247. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  41248. })(BABYLON || (BABYLON = {}));
  41249. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  41250. var BABYLON;
  41251. (function (BABYLON) {
  41252. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  41253. function FreeCameraKeyboardMoveInput() {
  41254. this._keys = new Array();
  41255. this.keysUp = [38];
  41256. this.keysDown = [40];
  41257. this.keysLeft = [37];
  41258. this.keysRight = [39];
  41259. }
  41260. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41261. var _this = this;
  41262. if (this._onCanvasBlurObserver) {
  41263. return;
  41264. }
  41265. this._scene = this.camera.getScene();
  41266. this._engine = this._scene.getEngine();
  41267. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41268. _this._keys = [];
  41269. });
  41270. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41271. var evt = info.event;
  41272. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41273. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41274. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41275. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41276. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41277. var index = _this._keys.indexOf(evt.keyCode);
  41278. if (index === -1) {
  41279. _this._keys.push(evt.keyCode);
  41280. }
  41281. if (!noPreventDefault) {
  41282. evt.preventDefault();
  41283. }
  41284. }
  41285. }
  41286. else {
  41287. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41288. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41289. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41290. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41291. var index = _this._keys.indexOf(evt.keyCode);
  41292. if (index >= 0) {
  41293. _this._keys.splice(index, 1);
  41294. }
  41295. if (!noPreventDefault) {
  41296. evt.preventDefault();
  41297. }
  41298. }
  41299. }
  41300. });
  41301. };
  41302. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41303. if (this._scene) {
  41304. if (this._onKeyboardObserver) {
  41305. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41306. }
  41307. if (this._onCanvasBlurObserver) {
  41308. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41309. }
  41310. this._onKeyboardObserver = null;
  41311. this._onCanvasBlurObserver = null;
  41312. }
  41313. this._keys = [];
  41314. };
  41315. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41316. if (this._onKeyboardObserver) {
  41317. var camera = this.camera;
  41318. // Keyboard
  41319. for (var index = 0; index < this._keys.length; index++) {
  41320. var keyCode = this._keys[index];
  41321. var speed = camera._computeLocalCameraSpeed();
  41322. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41323. camera._localDirection.copyFromFloats(-speed, 0, 0);
  41324. }
  41325. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41326. camera._localDirection.copyFromFloats(0, 0, speed);
  41327. }
  41328. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41329. camera._localDirection.copyFromFloats(speed, 0, 0);
  41330. }
  41331. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41332. camera._localDirection.copyFromFloats(0, 0, -speed);
  41333. }
  41334. if (camera.getScene().useRightHandedSystem) {
  41335. camera._localDirection.z *= -1;
  41336. }
  41337. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  41338. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  41339. camera.cameraDirection.addInPlace(camera._transformedDirection);
  41340. }
  41341. }
  41342. };
  41343. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  41344. return "FreeCameraKeyboardMoveInput";
  41345. };
  41346. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  41347. this._keys = [];
  41348. };
  41349. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41350. return "keyboard";
  41351. };
  41352. __decorate([
  41353. BABYLON.serialize()
  41354. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41355. __decorate([
  41356. BABYLON.serialize()
  41357. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41358. __decorate([
  41359. BABYLON.serialize()
  41360. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41361. __decorate([
  41362. BABYLON.serialize()
  41363. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41364. return FreeCameraKeyboardMoveInput;
  41365. }());
  41366. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  41367. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  41368. })(BABYLON || (BABYLON = {}));
  41369. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  41370. var BABYLON;
  41371. (function (BABYLON) {
  41372. var FreeCameraInputsManager = /** @class */ (function (_super) {
  41373. __extends(FreeCameraInputsManager, _super);
  41374. function FreeCameraInputsManager(camera) {
  41375. return _super.call(this, camera) || this;
  41376. }
  41377. FreeCameraInputsManager.prototype.addKeyboard = function () {
  41378. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  41379. return this;
  41380. };
  41381. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  41382. if (touchEnabled === void 0) { touchEnabled = true; }
  41383. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  41384. return this;
  41385. };
  41386. FreeCameraInputsManager.prototype.addGamepad = function () {
  41387. this.add(new BABYLON.FreeCameraGamepadInput());
  41388. return this;
  41389. };
  41390. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  41391. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  41392. return this;
  41393. };
  41394. FreeCameraInputsManager.prototype.addTouch = function () {
  41395. this.add(new BABYLON.FreeCameraTouchInput());
  41396. return this;
  41397. };
  41398. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  41399. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  41400. return this;
  41401. };
  41402. return FreeCameraInputsManager;
  41403. }(BABYLON.CameraInputsManager));
  41404. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  41405. })(BABYLON || (BABYLON = {}));
  41406. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  41407. var BABYLON;
  41408. (function (BABYLON) {
  41409. var FreeCamera = /** @class */ (function (_super) {
  41410. __extends(FreeCamera, _super);
  41411. function FreeCamera(name, position, scene) {
  41412. var _this = _super.call(this, name, position, scene) || this;
  41413. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  41414. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  41415. _this.checkCollisions = false;
  41416. _this.applyGravity = false;
  41417. _this._needMoveForGravity = false;
  41418. _this._oldPosition = BABYLON.Vector3.Zero();
  41419. _this._diffPosition = BABYLON.Vector3.Zero();
  41420. _this._newPosition = BABYLON.Vector3.Zero();
  41421. // Collisions
  41422. _this._collisionMask = -1;
  41423. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41424. if (collidedMesh === void 0) { collidedMesh = null; }
  41425. //TODO move this to the collision coordinator!
  41426. if (_this.getScene().workerCollisions)
  41427. newPosition.multiplyInPlace(_this._collider._radius);
  41428. var updatePosition = function (newPos) {
  41429. _this._newPosition.copyFrom(newPos);
  41430. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  41431. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  41432. _this.position.addInPlace(_this._diffPosition);
  41433. if (_this.onCollide && collidedMesh) {
  41434. _this.onCollide(collidedMesh);
  41435. }
  41436. }
  41437. };
  41438. updatePosition(newPosition);
  41439. };
  41440. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  41441. _this.inputs.addKeyboard().addMouse();
  41442. return _this;
  41443. }
  41444. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  41445. //-- begin properties for backward compatibility for inputs
  41446. /**
  41447. * Gets the input sensibility for a mouse input. (default is 2000.0)
  41448. * Higher values reduce sensitivity.
  41449. */
  41450. get: function () {
  41451. var mouse = this.inputs.attached["mouse"];
  41452. if (mouse)
  41453. return mouse.angularSensibility;
  41454. return 0;
  41455. },
  41456. /**
  41457. * Sets the input sensibility for a mouse input. (default is 2000.0)
  41458. * Higher values reduce sensitivity.
  41459. */
  41460. set: function (value) {
  41461. var mouse = this.inputs.attached["mouse"];
  41462. if (mouse)
  41463. mouse.angularSensibility = value;
  41464. },
  41465. enumerable: true,
  41466. configurable: true
  41467. });
  41468. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  41469. get: function () {
  41470. var keyboard = this.inputs.attached["keyboard"];
  41471. if (keyboard)
  41472. return keyboard.keysUp;
  41473. return [];
  41474. },
  41475. set: function (value) {
  41476. var keyboard = this.inputs.attached["keyboard"];
  41477. if (keyboard)
  41478. keyboard.keysUp = value;
  41479. },
  41480. enumerable: true,
  41481. configurable: true
  41482. });
  41483. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  41484. get: function () {
  41485. var keyboard = this.inputs.attached["keyboard"];
  41486. if (keyboard)
  41487. return keyboard.keysDown;
  41488. return [];
  41489. },
  41490. set: function (value) {
  41491. var keyboard = this.inputs.attached["keyboard"];
  41492. if (keyboard)
  41493. keyboard.keysDown = value;
  41494. },
  41495. enumerable: true,
  41496. configurable: true
  41497. });
  41498. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  41499. get: function () {
  41500. var keyboard = this.inputs.attached["keyboard"];
  41501. if (keyboard)
  41502. return keyboard.keysLeft;
  41503. return [];
  41504. },
  41505. set: function (value) {
  41506. var keyboard = this.inputs.attached["keyboard"];
  41507. if (keyboard)
  41508. keyboard.keysLeft = value;
  41509. },
  41510. enumerable: true,
  41511. configurable: true
  41512. });
  41513. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  41514. get: function () {
  41515. var keyboard = this.inputs.attached["keyboard"];
  41516. if (keyboard)
  41517. return keyboard.keysRight;
  41518. return [];
  41519. },
  41520. set: function (value) {
  41521. var keyboard = this.inputs.attached["keyboard"];
  41522. if (keyboard)
  41523. keyboard.keysRight = value;
  41524. },
  41525. enumerable: true,
  41526. configurable: true
  41527. });
  41528. // Controls
  41529. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  41530. this.inputs.attachElement(element, noPreventDefault);
  41531. };
  41532. FreeCamera.prototype.detachControl = function (element) {
  41533. this.inputs.detachElement(element);
  41534. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  41535. this.cameraRotation = new BABYLON.Vector2(0, 0);
  41536. };
  41537. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  41538. get: function () {
  41539. return this._collisionMask;
  41540. },
  41541. set: function (mask) {
  41542. this._collisionMask = !isNaN(mask) ? mask : -1;
  41543. },
  41544. enumerable: true,
  41545. configurable: true
  41546. });
  41547. FreeCamera.prototype._collideWithWorld = function (displacement) {
  41548. var globalPosition;
  41549. if (this.parent) {
  41550. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  41551. }
  41552. else {
  41553. globalPosition = this.position;
  41554. }
  41555. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  41556. this._oldPosition.addInPlace(this.ellipsoidOffset);
  41557. if (!this._collider) {
  41558. this._collider = new BABYLON.Collider();
  41559. }
  41560. this._collider._radius = this.ellipsoid;
  41561. this._collider.collisionMask = this._collisionMask;
  41562. //no need for clone, as long as gravity is not on.
  41563. var actualDisplacement = displacement;
  41564. //add gravity to the direction to prevent the dual-collision checking
  41565. if (this.applyGravity) {
  41566. //this prevents mending with cameraDirection, a global variable of the free camera class.
  41567. actualDisplacement = displacement.add(this.getScene().gravity);
  41568. }
  41569. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  41570. };
  41571. FreeCamera.prototype._checkInputs = function () {
  41572. if (!this._localDirection) {
  41573. this._localDirection = BABYLON.Vector3.Zero();
  41574. this._transformedDirection = BABYLON.Vector3.Zero();
  41575. }
  41576. this.inputs.checkInputs();
  41577. _super.prototype._checkInputs.call(this);
  41578. };
  41579. FreeCamera.prototype._decideIfNeedsToMove = function () {
  41580. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  41581. };
  41582. FreeCamera.prototype._updatePosition = function () {
  41583. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  41584. this._collideWithWorld(this.cameraDirection);
  41585. }
  41586. else {
  41587. _super.prototype._updatePosition.call(this);
  41588. }
  41589. };
  41590. FreeCamera.prototype.dispose = function () {
  41591. this.inputs.clear();
  41592. _super.prototype.dispose.call(this);
  41593. };
  41594. FreeCamera.prototype.getClassName = function () {
  41595. return "FreeCamera";
  41596. };
  41597. __decorate([
  41598. BABYLON.serializeAsVector3()
  41599. ], FreeCamera.prototype, "ellipsoid", void 0);
  41600. __decorate([
  41601. BABYLON.serializeAsVector3()
  41602. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  41603. __decorate([
  41604. BABYLON.serialize()
  41605. ], FreeCamera.prototype, "checkCollisions", void 0);
  41606. __decorate([
  41607. BABYLON.serialize()
  41608. ], FreeCamera.prototype, "applyGravity", void 0);
  41609. return FreeCamera;
  41610. }(BABYLON.TargetCamera));
  41611. BABYLON.FreeCamera = FreeCamera;
  41612. })(BABYLON || (BABYLON = {}));
  41613. //# sourceMappingURL=babylon.freeCamera.js.map
  41614. var BABYLON;
  41615. (function (BABYLON) {
  41616. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  41617. function ArcRotateCameraKeyboardMoveInput() {
  41618. this._keys = new Array();
  41619. this.keysUp = [38];
  41620. this.keysDown = [40];
  41621. this.keysLeft = [37];
  41622. this.keysRight = [39];
  41623. this.keysReset = [220];
  41624. this.panningSensibility = 50.0;
  41625. this.zoomingSensibility = 25.0;
  41626. this.useAltToZoom = true;
  41627. }
  41628. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41629. var _this = this;
  41630. if (this._onCanvasBlurObserver) {
  41631. return;
  41632. }
  41633. this._scene = this.camera.getScene();
  41634. this._engine = this._scene.getEngine();
  41635. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41636. _this._keys = [];
  41637. });
  41638. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41639. var evt = info.event;
  41640. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41641. _this._ctrlPressed = evt.ctrlKey;
  41642. _this._altPressed = evt.altKey;
  41643. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41644. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41645. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41646. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41647. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41648. var index = _this._keys.indexOf(evt.keyCode);
  41649. if (index === -1) {
  41650. _this._keys.push(evt.keyCode);
  41651. }
  41652. if (evt.preventDefault) {
  41653. if (!noPreventDefault) {
  41654. evt.preventDefault();
  41655. }
  41656. }
  41657. }
  41658. }
  41659. else {
  41660. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41661. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41662. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41663. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41664. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41665. var index = _this._keys.indexOf(evt.keyCode);
  41666. if (index >= 0) {
  41667. _this._keys.splice(index, 1);
  41668. }
  41669. if (evt.preventDefault) {
  41670. if (!noPreventDefault) {
  41671. evt.preventDefault();
  41672. }
  41673. }
  41674. }
  41675. }
  41676. });
  41677. };
  41678. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41679. if (this._scene) {
  41680. if (this._onKeyboardObserver) {
  41681. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41682. }
  41683. if (this._onCanvasBlurObserver) {
  41684. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41685. }
  41686. this._onKeyboardObserver = null;
  41687. this._onCanvasBlurObserver = null;
  41688. }
  41689. this._keys = [];
  41690. };
  41691. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41692. if (this._onKeyboardObserver) {
  41693. var camera = this.camera;
  41694. for (var index = 0; index < this._keys.length; index++) {
  41695. var keyCode = this._keys[index];
  41696. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41697. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41698. camera.inertialPanningX -= 1 / this.panningSensibility;
  41699. }
  41700. else {
  41701. camera.inertialAlphaOffset -= 0.01;
  41702. }
  41703. }
  41704. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41705. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41706. camera.inertialPanningY += 1 / this.panningSensibility;
  41707. }
  41708. else if (this._altPressed && this.useAltToZoom) {
  41709. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  41710. }
  41711. else {
  41712. camera.inertialBetaOffset -= 0.01;
  41713. }
  41714. }
  41715. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41716. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41717. camera.inertialPanningX += 1 / this.panningSensibility;
  41718. }
  41719. else {
  41720. camera.inertialAlphaOffset += 0.01;
  41721. }
  41722. }
  41723. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41724. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41725. camera.inertialPanningY -= 1 / this.panningSensibility;
  41726. }
  41727. else if (this._altPressed && this.useAltToZoom) {
  41728. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  41729. }
  41730. else {
  41731. camera.inertialBetaOffset += 0.01;
  41732. }
  41733. }
  41734. else if (this.keysReset.indexOf(keyCode) !== -1) {
  41735. camera.restoreState();
  41736. }
  41737. }
  41738. }
  41739. };
  41740. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  41741. return "ArcRotateCameraKeyboardMoveInput";
  41742. };
  41743. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41744. return "keyboard";
  41745. };
  41746. __decorate([
  41747. BABYLON.serialize()
  41748. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41749. __decorate([
  41750. BABYLON.serialize()
  41751. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41752. __decorate([
  41753. BABYLON.serialize()
  41754. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41755. __decorate([
  41756. BABYLON.serialize()
  41757. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41758. __decorate([
  41759. BABYLON.serialize()
  41760. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  41761. __decorate([
  41762. BABYLON.serialize()
  41763. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  41764. __decorate([
  41765. BABYLON.serialize()
  41766. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  41767. __decorate([
  41768. BABYLON.serialize()
  41769. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  41770. return ArcRotateCameraKeyboardMoveInput;
  41771. }());
  41772. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  41773. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  41774. })(BABYLON || (BABYLON = {}));
  41775. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  41776. var BABYLON;
  41777. (function (BABYLON) {
  41778. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  41779. function ArcRotateCameraMouseWheelInput() {
  41780. this.wheelPrecision = 3.0;
  41781. /**
  41782. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  41783. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  41784. */
  41785. this.wheelDeltaPercentage = 0;
  41786. }
  41787. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  41788. var _this = this;
  41789. this._wheel = function (p, s) {
  41790. //sanity check - this should be a PointerWheel event.
  41791. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  41792. return;
  41793. var event = p.event;
  41794. var delta = 0;
  41795. if (event.wheelDelta) {
  41796. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  41797. }
  41798. else if (event.detail) {
  41799. delta = -event.detail / _this.wheelPrecision;
  41800. }
  41801. if (delta)
  41802. _this.camera.inertialRadiusOffset += delta;
  41803. if (event.preventDefault) {
  41804. if (!noPreventDefault) {
  41805. event.preventDefault();
  41806. }
  41807. }
  41808. };
  41809. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  41810. };
  41811. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  41812. if (this._observer && element) {
  41813. this.camera.getScene().onPointerObservable.remove(this._observer);
  41814. this._observer = null;
  41815. this._wheel = null;
  41816. }
  41817. };
  41818. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  41819. return "ArcRotateCameraMouseWheelInput";
  41820. };
  41821. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  41822. return "mousewheel";
  41823. };
  41824. __decorate([
  41825. BABYLON.serialize()
  41826. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  41827. __decorate([
  41828. BABYLON.serialize()
  41829. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  41830. return ArcRotateCameraMouseWheelInput;
  41831. }());
  41832. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  41833. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  41834. })(BABYLON || (BABYLON = {}));
  41835. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  41836. var BABYLON;
  41837. (function (BABYLON) {
  41838. var ArcRotateCameraPointersInput = /** @class */ (function () {
  41839. function ArcRotateCameraPointersInput() {
  41840. this.buttons = [0, 1, 2];
  41841. this.angularSensibilityX = 1000.0;
  41842. this.angularSensibilityY = 1000.0;
  41843. this.pinchPrecision = 12.0;
  41844. /**
  41845. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  41846. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  41847. */
  41848. this.pinchDeltaPercentage = 0;
  41849. this.panningSensibility = 1000.0;
  41850. this.multiTouchPanning = true;
  41851. this.multiTouchPanAndZoom = true;
  41852. this._isPanClick = false;
  41853. this.pinchInwards = true;
  41854. }
  41855. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  41856. var _this = this;
  41857. var engine = this.camera.getEngine();
  41858. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  41859. var pointA = null;
  41860. var pointB = null;
  41861. var previousPinchSquaredDistance = 0;
  41862. var initialDistance = 0;
  41863. var twoFingerActivityCount = 0;
  41864. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  41865. this._pointerInput = function (p, s) {
  41866. var evt = p.event;
  41867. var isTouch = p.event.pointerType === "touch";
  41868. if (engine.isInVRExclusivePointerMode) {
  41869. return;
  41870. }
  41871. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41872. return;
  41873. }
  41874. var srcElement = (evt.srcElement || evt.target);
  41875. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41876. try {
  41877. srcElement.setPointerCapture(evt.pointerId);
  41878. }
  41879. catch (e) {
  41880. //Nothing to do with the error. Execution will continue.
  41881. }
  41882. // Manage panning with pan button click
  41883. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  41884. // manage pointers
  41885. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  41886. if (pointA === null) {
  41887. pointA = cacheSoloPointer;
  41888. }
  41889. else if (pointB === null) {
  41890. pointB = cacheSoloPointer;
  41891. }
  41892. if (!noPreventDefault) {
  41893. evt.preventDefault();
  41894. element.focus();
  41895. }
  41896. }
  41897. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  41898. _this.camera.restoreState();
  41899. }
  41900. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41901. try {
  41902. srcElement.releasePointerCapture(evt.pointerId);
  41903. }
  41904. catch (e) {
  41905. //Nothing to do with the error.
  41906. }
  41907. cacheSoloPointer = null;
  41908. previousPinchSquaredDistance = 0;
  41909. previousMultiTouchPanPosition.isPaning = false;
  41910. previousMultiTouchPanPosition.isPinching = false;
  41911. twoFingerActivityCount = 0;
  41912. initialDistance = 0;
  41913. if (!isTouch) {
  41914. pointB = null; // Mouse and pen are mono pointer
  41915. }
  41916. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  41917. //but emptying completly pointers collection is required to fix a bug on iPhone :
  41918. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  41919. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  41920. if (engine.badOS) {
  41921. pointA = pointB = null;
  41922. }
  41923. else {
  41924. //only remove the impacted pointer in case of multitouch allowing on most
  41925. //platforms switching from rotate to zoom and pan seamlessly.
  41926. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  41927. pointA = pointB;
  41928. pointB = null;
  41929. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41930. }
  41931. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  41932. pointB = null;
  41933. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41934. }
  41935. else {
  41936. pointA = pointB = null;
  41937. }
  41938. }
  41939. if (!noPreventDefault) {
  41940. evt.preventDefault();
  41941. }
  41942. }
  41943. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41944. if (!noPreventDefault) {
  41945. evt.preventDefault();
  41946. }
  41947. // One button down
  41948. if (pointA && pointB === null && cacheSoloPointer) {
  41949. if (_this.panningSensibility !== 0 &&
  41950. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  41951. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  41952. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  41953. }
  41954. else {
  41955. var offsetX = evt.clientX - cacheSoloPointer.x;
  41956. var offsetY = evt.clientY - cacheSoloPointer.y;
  41957. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41958. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41959. }
  41960. cacheSoloPointer.x = evt.clientX;
  41961. cacheSoloPointer.y = evt.clientY;
  41962. }
  41963. else if (pointA && pointB) {
  41964. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41965. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41966. ed.x = evt.clientX;
  41967. ed.y = evt.clientY;
  41968. var direction = _this.pinchInwards ? 1 : -1;
  41969. var distX = pointA.x - pointB.x;
  41970. var distY = pointA.y - pointB.y;
  41971. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41972. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41973. if (previousPinchSquaredDistance === 0) {
  41974. initialDistance = pinchDistance;
  41975. previousPinchSquaredDistance = pinchSquaredDistance;
  41976. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41977. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41978. return;
  41979. }
  41980. if (_this.multiTouchPanAndZoom) {
  41981. if (_this.pinchDeltaPercentage) {
  41982. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41983. }
  41984. else {
  41985. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41986. (_this.pinchPrecision *
  41987. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41988. direction);
  41989. }
  41990. if (_this.panningSensibility !== 0) {
  41991. var pointersCenterX = (pointA.x + pointB.x) / 2;
  41992. var pointersCenterY = (pointA.y + pointB.y) / 2;
  41993. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  41994. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  41995. previousMultiTouchPanPosition.x = pointersCenterX;
  41996. previousMultiTouchPanPosition.y = pointersCenterY;
  41997. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  41998. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  41999. }
  42000. }
  42001. else {
  42002. twoFingerActivityCount++;
  42003. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  42004. if (_this.pinchDeltaPercentage) {
  42005. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  42006. }
  42007. else {
  42008. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  42009. (_this.pinchPrecision *
  42010. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  42011. direction);
  42012. }
  42013. previousMultiTouchPanPosition.isPaning = false;
  42014. previousMultiTouchPanPosition.isPinching = true;
  42015. }
  42016. else {
  42017. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  42018. if (!previousMultiTouchPanPosition.isPaning) {
  42019. previousMultiTouchPanPosition.isPaning = true;
  42020. previousMultiTouchPanPosition.isPinching = false;
  42021. previousMultiTouchPanPosition.x = ed.x;
  42022. previousMultiTouchPanPosition.y = ed.y;
  42023. return;
  42024. }
  42025. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  42026. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  42027. }
  42028. }
  42029. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  42030. previousMultiTouchPanPosition.x = ed.x;
  42031. previousMultiTouchPanPosition.y = ed.y;
  42032. }
  42033. }
  42034. previousPinchSquaredDistance = pinchSquaredDistance;
  42035. }
  42036. }
  42037. };
  42038. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  42039. this._onContextMenu = function (evt) {
  42040. evt.preventDefault();
  42041. };
  42042. if (!this.camera._useCtrlForPanning) {
  42043. element.addEventListener("contextmenu", this._onContextMenu, false);
  42044. }
  42045. this._onLostFocus = function () {
  42046. //this._keys = [];
  42047. pointA = pointB = null;
  42048. previousPinchSquaredDistance = 0;
  42049. previousMultiTouchPanPosition.isPaning = false;
  42050. previousMultiTouchPanPosition.isPinching = false;
  42051. twoFingerActivityCount = 0;
  42052. cacheSoloPointer = null;
  42053. initialDistance = 0;
  42054. };
  42055. this._onMouseMove = function (evt) {
  42056. if (!engine.isPointerLock) {
  42057. return;
  42058. }
  42059. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42060. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42061. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  42062. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  42063. if (!noPreventDefault) {
  42064. evt.preventDefault();
  42065. }
  42066. };
  42067. this._onGestureStart = function (e) {
  42068. if (window.MSGesture === undefined) {
  42069. return;
  42070. }
  42071. if (!_this._MSGestureHandler) {
  42072. _this._MSGestureHandler = new MSGesture();
  42073. _this._MSGestureHandler.target = element;
  42074. }
  42075. _this._MSGestureHandler.addPointer(e.pointerId);
  42076. };
  42077. this._onGesture = function (e) {
  42078. _this.camera.radius *= e.scale;
  42079. if (e.preventDefault) {
  42080. if (!noPreventDefault) {
  42081. e.stopPropagation();
  42082. e.preventDefault();
  42083. }
  42084. }
  42085. };
  42086. element.addEventListener("mousemove", this._onMouseMove, false);
  42087. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  42088. element.addEventListener("MSGestureChange", this._onGesture, false);
  42089. BABYLON.Tools.RegisterTopRootEvents([
  42090. { name: "blur", handler: this._onLostFocus }
  42091. ]);
  42092. };
  42093. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  42094. if (this._onLostFocus) {
  42095. BABYLON.Tools.UnregisterTopRootEvents([
  42096. { name: "blur", handler: this._onLostFocus }
  42097. ]);
  42098. }
  42099. if (element && this._observer) {
  42100. this.camera.getScene().onPointerObservable.remove(this._observer);
  42101. this._observer = null;
  42102. if (this._onContextMenu) {
  42103. element.removeEventListener("contextmenu", this._onContextMenu);
  42104. }
  42105. if (this._onMouseMove) {
  42106. element.removeEventListener("mousemove", this._onMouseMove);
  42107. }
  42108. if (this._onGestureStart) {
  42109. element.removeEventListener("MSPointerDown", this._onGestureStart);
  42110. }
  42111. if (this._onGesture) {
  42112. element.removeEventListener("MSGestureChange", this._onGesture);
  42113. }
  42114. this._isPanClick = false;
  42115. this.pinchInwards = true;
  42116. this._onMouseMove = null;
  42117. this._onGestureStart = null;
  42118. this._onGesture = null;
  42119. this._MSGestureHandler = null;
  42120. this._onLostFocus = null;
  42121. this._onContextMenu = null;
  42122. }
  42123. };
  42124. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  42125. return "ArcRotateCameraPointersInput";
  42126. };
  42127. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  42128. return "pointers";
  42129. };
  42130. __decorate([
  42131. BABYLON.serialize()
  42132. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  42133. __decorate([
  42134. BABYLON.serialize()
  42135. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  42136. __decorate([
  42137. BABYLON.serialize()
  42138. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  42139. __decorate([
  42140. BABYLON.serialize()
  42141. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  42142. __decorate([
  42143. BABYLON.serialize()
  42144. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  42145. __decorate([
  42146. BABYLON.serialize()
  42147. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  42148. __decorate([
  42149. BABYLON.serialize()
  42150. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  42151. __decorate([
  42152. BABYLON.serialize()
  42153. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  42154. return ArcRotateCameraPointersInput;
  42155. }());
  42156. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  42157. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  42158. })(BABYLON || (BABYLON = {}));
  42159. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  42160. var BABYLON;
  42161. (function (BABYLON) {
  42162. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  42163. __extends(ArcRotateCameraInputsManager, _super);
  42164. function ArcRotateCameraInputsManager(camera) {
  42165. return _super.call(this, camera) || this;
  42166. }
  42167. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  42168. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  42169. return this;
  42170. };
  42171. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  42172. this.add(new BABYLON.ArcRotateCameraPointersInput());
  42173. return this;
  42174. };
  42175. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  42176. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  42177. return this;
  42178. };
  42179. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  42180. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  42181. return this;
  42182. };
  42183. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  42184. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  42185. return this;
  42186. };
  42187. return ArcRotateCameraInputsManager;
  42188. }(BABYLON.CameraInputsManager));
  42189. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  42190. })(BABYLON || (BABYLON = {}));
  42191. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  42192. var BABYLON;
  42193. (function (BABYLON) {
  42194. var ArcRotateCamera = /** @class */ (function (_super) {
  42195. __extends(ArcRotateCamera, _super);
  42196. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  42197. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  42198. _this.inertialAlphaOffset = 0;
  42199. _this.inertialBetaOffset = 0;
  42200. _this.inertialRadiusOffset = 0;
  42201. _this.lowerAlphaLimit = null;
  42202. _this.upperAlphaLimit = null;
  42203. _this.lowerBetaLimit = 0.01;
  42204. _this.upperBetaLimit = Math.PI;
  42205. _this.lowerRadiusLimit = null;
  42206. _this.upperRadiusLimit = null;
  42207. _this.inertialPanningX = 0;
  42208. _this.inertialPanningY = 0;
  42209. _this.pinchToPanMaxDistance = 20;
  42210. _this.panningDistanceLimit = null;
  42211. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  42212. _this.panningInertia = 0.9;
  42213. //-- end properties for backward compatibility for inputs
  42214. _this.zoomOnFactor = 1;
  42215. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  42216. _this.allowUpsideDown = true;
  42217. _this._viewMatrix = new BABYLON.Matrix();
  42218. // Panning
  42219. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  42220. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  42221. _this.checkCollisions = false;
  42222. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  42223. _this._previousPosition = BABYLON.Vector3.Zero();
  42224. _this._collisionVelocity = BABYLON.Vector3.Zero();
  42225. _this._newPosition = BABYLON.Vector3.Zero();
  42226. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42227. if (collidedMesh === void 0) { collidedMesh = null; }
  42228. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  42229. newPosition.multiplyInPlace(_this._collider._radius);
  42230. }
  42231. if (!collidedMesh) {
  42232. _this._previousPosition.copyFrom(_this.position);
  42233. }
  42234. else {
  42235. _this.setPosition(newPosition);
  42236. if (_this.onCollide) {
  42237. _this.onCollide(collidedMesh);
  42238. }
  42239. }
  42240. // Recompute because of constraints
  42241. var cosa = Math.cos(_this.alpha);
  42242. var sina = Math.sin(_this.alpha);
  42243. var cosb = Math.cos(_this.beta);
  42244. var sinb = Math.sin(_this.beta);
  42245. if (sinb === 0) {
  42246. sinb = 0.0001;
  42247. }
  42248. var target = _this._getTargetPosition();
  42249. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  42250. _this.position.copyFrom(_this._newPosition);
  42251. var up = _this.upVector;
  42252. if (_this.allowUpsideDown && _this.beta < 0) {
  42253. up = up.clone();
  42254. up = up.negate();
  42255. }
  42256. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  42257. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  42258. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  42259. _this._collisionTriggered = false;
  42260. };
  42261. _this._target = BABYLON.Vector3.Zero();
  42262. if (target) {
  42263. _this.setTarget(target);
  42264. }
  42265. _this.alpha = alpha;
  42266. _this.beta = beta;
  42267. _this.radius = radius;
  42268. _this.getViewMatrix();
  42269. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  42270. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  42271. return _this;
  42272. }
  42273. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  42274. get: function () {
  42275. return this._target;
  42276. },
  42277. set: function (value) {
  42278. this.setTarget(value);
  42279. },
  42280. enumerable: true,
  42281. configurable: true
  42282. });
  42283. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  42284. //-- begin properties for backward compatibility for inputs
  42285. get: function () {
  42286. var pointers = this.inputs.attached["pointers"];
  42287. if (pointers)
  42288. return pointers.angularSensibilityX;
  42289. return 0;
  42290. },
  42291. set: function (value) {
  42292. var pointers = this.inputs.attached["pointers"];
  42293. if (pointers) {
  42294. pointers.angularSensibilityX = value;
  42295. }
  42296. },
  42297. enumerable: true,
  42298. configurable: true
  42299. });
  42300. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  42301. get: function () {
  42302. var pointers = this.inputs.attached["pointers"];
  42303. if (pointers)
  42304. return pointers.angularSensibilityY;
  42305. return 0;
  42306. },
  42307. set: function (value) {
  42308. var pointers = this.inputs.attached["pointers"];
  42309. if (pointers) {
  42310. pointers.angularSensibilityY = value;
  42311. }
  42312. },
  42313. enumerable: true,
  42314. configurable: true
  42315. });
  42316. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  42317. get: function () {
  42318. var pointers = this.inputs.attached["pointers"];
  42319. if (pointers)
  42320. return pointers.pinchPrecision;
  42321. return 0;
  42322. },
  42323. set: function (value) {
  42324. var pointers = this.inputs.attached["pointers"];
  42325. if (pointers) {
  42326. pointers.pinchPrecision = value;
  42327. }
  42328. },
  42329. enumerable: true,
  42330. configurable: true
  42331. });
  42332. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  42333. get: function () {
  42334. var pointers = this.inputs.attached["pointers"];
  42335. if (pointers)
  42336. return pointers.pinchDeltaPercentage;
  42337. return 0;
  42338. },
  42339. set: function (value) {
  42340. var pointers = this.inputs.attached["pointers"];
  42341. if (pointers) {
  42342. pointers.pinchDeltaPercentage = value;
  42343. }
  42344. },
  42345. enumerable: true,
  42346. configurable: true
  42347. });
  42348. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  42349. get: function () {
  42350. var pointers = this.inputs.attached["pointers"];
  42351. if (pointers)
  42352. return pointers.panningSensibility;
  42353. return 0;
  42354. },
  42355. set: function (value) {
  42356. var pointers = this.inputs.attached["pointers"];
  42357. if (pointers) {
  42358. pointers.panningSensibility = value;
  42359. }
  42360. },
  42361. enumerable: true,
  42362. configurable: true
  42363. });
  42364. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  42365. get: function () {
  42366. var keyboard = this.inputs.attached["keyboard"];
  42367. if (keyboard)
  42368. return keyboard.keysUp;
  42369. return [];
  42370. },
  42371. set: function (value) {
  42372. var keyboard = this.inputs.attached["keyboard"];
  42373. if (keyboard)
  42374. keyboard.keysUp = value;
  42375. },
  42376. enumerable: true,
  42377. configurable: true
  42378. });
  42379. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  42380. get: function () {
  42381. var keyboard = this.inputs.attached["keyboard"];
  42382. if (keyboard)
  42383. return keyboard.keysDown;
  42384. return [];
  42385. },
  42386. set: function (value) {
  42387. var keyboard = this.inputs.attached["keyboard"];
  42388. if (keyboard)
  42389. keyboard.keysDown = value;
  42390. },
  42391. enumerable: true,
  42392. configurable: true
  42393. });
  42394. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  42395. get: function () {
  42396. var keyboard = this.inputs.attached["keyboard"];
  42397. if (keyboard)
  42398. return keyboard.keysLeft;
  42399. return [];
  42400. },
  42401. set: function (value) {
  42402. var keyboard = this.inputs.attached["keyboard"];
  42403. if (keyboard)
  42404. keyboard.keysLeft = value;
  42405. },
  42406. enumerable: true,
  42407. configurable: true
  42408. });
  42409. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  42410. get: function () {
  42411. var keyboard = this.inputs.attached["keyboard"];
  42412. if (keyboard)
  42413. return keyboard.keysRight;
  42414. return [];
  42415. },
  42416. set: function (value) {
  42417. var keyboard = this.inputs.attached["keyboard"];
  42418. if (keyboard)
  42419. keyboard.keysRight = value;
  42420. },
  42421. enumerable: true,
  42422. configurable: true
  42423. });
  42424. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  42425. get: function () {
  42426. var mousewheel = this.inputs.attached["mousewheel"];
  42427. if (mousewheel)
  42428. return mousewheel.wheelPrecision;
  42429. return 0;
  42430. },
  42431. set: function (value) {
  42432. var mousewheel = this.inputs.attached["mousewheel"];
  42433. if (mousewheel)
  42434. mousewheel.wheelPrecision = value;
  42435. },
  42436. enumerable: true,
  42437. configurable: true
  42438. });
  42439. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  42440. get: function () {
  42441. var mousewheel = this.inputs.attached["mousewheel"];
  42442. if (mousewheel)
  42443. return mousewheel.wheelDeltaPercentage;
  42444. return 0;
  42445. },
  42446. set: function (value) {
  42447. var mousewheel = this.inputs.attached["mousewheel"];
  42448. if (mousewheel)
  42449. mousewheel.wheelDeltaPercentage = value;
  42450. },
  42451. enumerable: true,
  42452. configurable: true
  42453. });
  42454. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  42455. get: function () {
  42456. return this._bouncingBehavior;
  42457. },
  42458. enumerable: true,
  42459. configurable: true
  42460. });
  42461. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  42462. get: function () {
  42463. return this._bouncingBehavior != null;
  42464. },
  42465. set: function (value) {
  42466. if (value === this.useBouncingBehavior) {
  42467. return;
  42468. }
  42469. if (value) {
  42470. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  42471. this.addBehavior(this._bouncingBehavior);
  42472. }
  42473. else if (this._bouncingBehavior) {
  42474. this.removeBehavior(this._bouncingBehavior);
  42475. this._bouncingBehavior = null;
  42476. }
  42477. },
  42478. enumerable: true,
  42479. configurable: true
  42480. });
  42481. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  42482. get: function () {
  42483. return this._framingBehavior;
  42484. },
  42485. enumerable: true,
  42486. configurable: true
  42487. });
  42488. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  42489. get: function () {
  42490. return this._framingBehavior != null;
  42491. },
  42492. set: function (value) {
  42493. if (value === this.useFramingBehavior) {
  42494. return;
  42495. }
  42496. if (value) {
  42497. this._framingBehavior = new BABYLON.FramingBehavior();
  42498. this.addBehavior(this._framingBehavior);
  42499. }
  42500. else if (this._framingBehavior) {
  42501. this.removeBehavior(this._framingBehavior);
  42502. this._framingBehavior = null;
  42503. }
  42504. },
  42505. enumerable: true,
  42506. configurable: true
  42507. });
  42508. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  42509. get: function () {
  42510. return this._autoRotationBehavior;
  42511. },
  42512. enumerable: true,
  42513. configurable: true
  42514. });
  42515. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  42516. get: function () {
  42517. return this._autoRotationBehavior != null;
  42518. },
  42519. set: function (value) {
  42520. if (value === this.useAutoRotationBehavior) {
  42521. return;
  42522. }
  42523. if (value) {
  42524. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  42525. this.addBehavior(this._autoRotationBehavior);
  42526. }
  42527. else if (this._autoRotationBehavior) {
  42528. this.removeBehavior(this._autoRotationBehavior);
  42529. this._autoRotationBehavior = null;
  42530. }
  42531. },
  42532. enumerable: true,
  42533. configurable: true
  42534. });
  42535. // Cache
  42536. ArcRotateCamera.prototype._initCache = function () {
  42537. _super.prototype._initCache.call(this);
  42538. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42539. this._cache.alpha = undefined;
  42540. this._cache.beta = undefined;
  42541. this._cache.radius = undefined;
  42542. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  42543. };
  42544. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  42545. if (!ignoreParentClass) {
  42546. _super.prototype._updateCache.call(this);
  42547. }
  42548. this._cache._target.copyFrom(this._getTargetPosition());
  42549. this._cache.alpha = this.alpha;
  42550. this._cache.beta = this.beta;
  42551. this._cache.radius = this.radius;
  42552. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  42553. };
  42554. ArcRotateCamera.prototype._getTargetPosition = function () {
  42555. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  42556. var pos = this._targetHost.getAbsolutePosition();
  42557. if (this._targetBoundingCenter) {
  42558. pos.addToRef(this._targetBoundingCenter, this._target);
  42559. }
  42560. else {
  42561. this._target.copyFrom(pos);
  42562. }
  42563. }
  42564. var lockedTargetPosition = this._getLockedTargetPosition();
  42565. if (lockedTargetPosition) {
  42566. return lockedTargetPosition;
  42567. }
  42568. return this._target;
  42569. };
  42570. ArcRotateCamera.prototype.storeState = function () {
  42571. this._storedAlpha = this.alpha;
  42572. this._storedBeta = this.beta;
  42573. this._storedRadius = this.radius;
  42574. this._storedTarget = this._getTargetPosition().clone();
  42575. return _super.prototype.storeState.call(this);
  42576. };
  42577. /**
  42578. * Restored camera state. You must call storeState() first
  42579. */
  42580. ArcRotateCamera.prototype._restoreStateValues = function () {
  42581. if (!_super.prototype._restoreStateValues.call(this)) {
  42582. return false;
  42583. }
  42584. this.alpha = this._storedAlpha;
  42585. this.beta = this._storedBeta;
  42586. this.radius = this._storedRadius;
  42587. this.setTarget(this._storedTarget.clone());
  42588. this.inertialAlphaOffset = 0;
  42589. this.inertialBetaOffset = 0;
  42590. this.inertialRadiusOffset = 0;
  42591. this.inertialPanningX = 0;
  42592. this.inertialPanningY = 0;
  42593. return true;
  42594. };
  42595. // Synchronized
  42596. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  42597. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  42598. return false;
  42599. return this._cache._target.equals(this._getTargetPosition())
  42600. && this._cache.alpha === this.alpha
  42601. && this._cache.beta === this.beta
  42602. && this._cache.radius === this.radius
  42603. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  42604. };
  42605. // Methods
  42606. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  42607. var _this = this;
  42608. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  42609. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  42610. this._useCtrlForPanning = useCtrlForPanning;
  42611. this._panningMouseButton = panningMouseButton;
  42612. this.inputs.attachElement(element, noPreventDefault);
  42613. this._reset = function () {
  42614. _this.inertialAlphaOffset = 0;
  42615. _this.inertialBetaOffset = 0;
  42616. _this.inertialRadiusOffset = 0;
  42617. _this.inertialPanningX = 0;
  42618. _this.inertialPanningY = 0;
  42619. };
  42620. };
  42621. ArcRotateCamera.prototype.detachControl = function (element) {
  42622. this.inputs.detachElement(element);
  42623. if (this._reset) {
  42624. this._reset();
  42625. }
  42626. };
  42627. ArcRotateCamera.prototype._checkInputs = function () {
  42628. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  42629. if (this._collisionTriggered) {
  42630. return;
  42631. }
  42632. this.inputs.checkInputs();
  42633. // Inertia
  42634. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  42635. if (this.getScene().useRightHandedSystem) {
  42636. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42637. }
  42638. else {
  42639. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42640. }
  42641. this.beta += this.inertialBetaOffset;
  42642. this.radius -= this.inertialRadiusOffset;
  42643. this.inertialAlphaOffset *= this.inertia;
  42644. this.inertialBetaOffset *= this.inertia;
  42645. this.inertialRadiusOffset *= this.inertia;
  42646. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  42647. this.inertialAlphaOffset = 0;
  42648. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  42649. this.inertialBetaOffset = 0;
  42650. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  42651. this.inertialRadiusOffset = 0;
  42652. }
  42653. // Panning inertia
  42654. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  42655. if (!this._localDirection) {
  42656. this._localDirection = BABYLON.Vector3.Zero();
  42657. this._transformedDirection = BABYLON.Vector3.Zero();
  42658. }
  42659. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  42660. this._localDirection.multiplyInPlace(this.panningAxis);
  42661. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  42662. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  42663. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  42664. if (!this.panningAxis.y) {
  42665. this._transformedDirection.y = 0;
  42666. }
  42667. if (!this._targetHost) {
  42668. if (this.panningDistanceLimit) {
  42669. this._transformedDirection.addInPlace(this._target);
  42670. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  42671. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  42672. this._target.copyFrom(this._transformedDirection);
  42673. }
  42674. }
  42675. else {
  42676. this._target.addInPlace(this._transformedDirection);
  42677. }
  42678. }
  42679. this.inertialPanningX *= this.panningInertia;
  42680. this.inertialPanningY *= this.panningInertia;
  42681. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  42682. this.inertialPanningX = 0;
  42683. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  42684. this.inertialPanningY = 0;
  42685. }
  42686. // Limits
  42687. this._checkLimits();
  42688. _super.prototype._checkInputs.call(this);
  42689. };
  42690. ArcRotateCamera.prototype._checkLimits = function () {
  42691. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  42692. if (this.allowUpsideDown && this.beta > Math.PI) {
  42693. this.beta = this.beta - (2 * Math.PI);
  42694. }
  42695. }
  42696. else {
  42697. if (this.beta < this.lowerBetaLimit) {
  42698. this.beta = this.lowerBetaLimit;
  42699. }
  42700. }
  42701. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  42702. if (this.allowUpsideDown && this.beta < -Math.PI) {
  42703. this.beta = this.beta + (2 * Math.PI);
  42704. }
  42705. }
  42706. else {
  42707. if (this.beta > this.upperBetaLimit) {
  42708. this.beta = this.upperBetaLimit;
  42709. }
  42710. }
  42711. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  42712. this.alpha = this.lowerAlphaLimit;
  42713. }
  42714. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  42715. this.alpha = this.upperAlphaLimit;
  42716. }
  42717. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  42718. this.radius = this.lowerRadiusLimit;
  42719. }
  42720. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  42721. this.radius = this.upperRadiusLimit;
  42722. }
  42723. };
  42724. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  42725. var radiusv3 = this.position.subtract(this._getTargetPosition());
  42726. this.radius = radiusv3.length();
  42727. if (this.radius === 0) {
  42728. this.radius = 0.0001; // Just to avoid division by zero
  42729. }
  42730. // Alpha
  42731. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  42732. if (radiusv3.z < 0) {
  42733. this.alpha = 2 * Math.PI - this.alpha;
  42734. }
  42735. // Beta
  42736. this.beta = Math.acos(radiusv3.y / this.radius);
  42737. this._checkLimits();
  42738. };
  42739. ArcRotateCamera.prototype.setPosition = function (position) {
  42740. if (this.position.equals(position)) {
  42741. return;
  42742. }
  42743. this.position.copyFrom(position);
  42744. this.rebuildAnglesAndRadius();
  42745. };
  42746. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  42747. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  42748. if (allowSamePosition === void 0) { allowSamePosition = false; }
  42749. if (target.getBoundingInfo) {
  42750. if (toBoundingCenter) {
  42751. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  42752. }
  42753. else {
  42754. this._targetBoundingCenter = null;
  42755. }
  42756. this._targetHost = target;
  42757. this._target = this._getTargetPosition();
  42758. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  42759. }
  42760. else {
  42761. var newTarget = target;
  42762. var currentTarget = this._getTargetPosition();
  42763. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  42764. return;
  42765. }
  42766. this._targetHost = null;
  42767. this._target = newTarget;
  42768. this._targetBoundingCenter = null;
  42769. this.onMeshTargetChangedObservable.notifyObservers(null);
  42770. }
  42771. this.rebuildAnglesAndRadius();
  42772. };
  42773. ArcRotateCamera.prototype._getViewMatrix = function () {
  42774. // Compute
  42775. var cosa = Math.cos(this.alpha);
  42776. var sina = Math.sin(this.alpha);
  42777. var cosb = Math.cos(this.beta);
  42778. var sinb = Math.sin(this.beta);
  42779. if (sinb === 0) {
  42780. sinb = 0.0001;
  42781. }
  42782. var target = this._getTargetPosition();
  42783. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  42784. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  42785. if (!this._collider) {
  42786. this._collider = new BABYLON.Collider();
  42787. }
  42788. this._collider._radius = this.collisionRadius;
  42789. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  42790. this._collisionTriggered = true;
  42791. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42792. }
  42793. else {
  42794. this.position.copyFrom(this._newPosition);
  42795. var up = this.upVector;
  42796. if (this.allowUpsideDown && sinb < 0) {
  42797. up = up.clone();
  42798. up = up.negate();
  42799. }
  42800. if (this.getScene().useRightHandedSystem) {
  42801. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  42802. }
  42803. else {
  42804. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  42805. }
  42806. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  42807. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  42808. }
  42809. this._currentTarget = target;
  42810. return this._viewMatrix;
  42811. };
  42812. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  42813. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42814. meshes = meshes || this.getScene().meshes;
  42815. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  42816. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  42817. this.radius = distance * this.zoomOnFactor;
  42818. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  42819. };
  42820. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  42821. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42822. var meshesOrMinMaxVector;
  42823. var distance;
  42824. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  42825. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  42826. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  42827. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  42828. }
  42829. else {
  42830. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  42831. meshesOrMinMaxVector = minMaxVectorAndDistance;
  42832. distance = minMaxVectorAndDistance.distance;
  42833. }
  42834. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  42835. if (!doNotUpdateMaxZ) {
  42836. this.maxZ = distance * 2;
  42837. }
  42838. };
  42839. /**
  42840. * @override
  42841. * Override Camera.createRigCamera
  42842. */
  42843. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42844. var alphaShift = 0;
  42845. switch (this.cameraRigMode) {
  42846. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42847. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42848. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42849. case BABYLON.Camera.RIG_MODE_VR:
  42850. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  42851. break;
  42852. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42853. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  42854. break;
  42855. }
  42856. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  42857. rigCam._cameraRigParams = {};
  42858. return rigCam;
  42859. };
  42860. /**
  42861. * @override
  42862. * Override Camera._updateRigCameras
  42863. */
  42864. ArcRotateCamera.prototype._updateRigCameras = function () {
  42865. var camLeft = this._rigCameras[0];
  42866. var camRight = this._rigCameras[1];
  42867. camLeft.beta = camRight.beta = this.beta;
  42868. camLeft.radius = camRight.radius = this.radius;
  42869. switch (this.cameraRigMode) {
  42870. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42871. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42872. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42873. case BABYLON.Camera.RIG_MODE_VR:
  42874. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42875. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42876. break;
  42877. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42878. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42879. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42880. break;
  42881. }
  42882. _super.prototype._updateRigCameras.call(this);
  42883. };
  42884. ArcRotateCamera.prototype.dispose = function () {
  42885. this.inputs.clear();
  42886. _super.prototype.dispose.call(this);
  42887. };
  42888. ArcRotateCamera.prototype.getClassName = function () {
  42889. return "ArcRotateCamera";
  42890. };
  42891. __decorate([
  42892. BABYLON.serialize()
  42893. ], ArcRotateCamera.prototype, "alpha", void 0);
  42894. __decorate([
  42895. BABYLON.serialize()
  42896. ], ArcRotateCamera.prototype, "beta", void 0);
  42897. __decorate([
  42898. BABYLON.serialize()
  42899. ], ArcRotateCamera.prototype, "radius", void 0);
  42900. __decorate([
  42901. BABYLON.serializeAsVector3("target")
  42902. ], ArcRotateCamera.prototype, "_target", void 0);
  42903. __decorate([
  42904. BABYLON.serialize()
  42905. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  42906. __decorate([
  42907. BABYLON.serialize()
  42908. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  42909. __decorate([
  42910. BABYLON.serialize()
  42911. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  42912. __decorate([
  42913. BABYLON.serialize()
  42914. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  42915. __decorate([
  42916. BABYLON.serialize()
  42917. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  42918. __decorate([
  42919. BABYLON.serialize()
  42920. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  42921. __decorate([
  42922. BABYLON.serialize()
  42923. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  42924. __decorate([
  42925. BABYLON.serialize()
  42926. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  42927. __decorate([
  42928. BABYLON.serialize()
  42929. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  42930. __decorate([
  42931. BABYLON.serialize()
  42932. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  42933. __decorate([
  42934. BABYLON.serialize()
  42935. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  42936. __decorate([
  42937. BABYLON.serialize()
  42938. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  42939. __decorate([
  42940. BABYLON.serialize()
  42941. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  42942. __decorate([
  42943. BABYLON.serializeAsVector3()
  42944. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  42945. __decorate([
  42946. BABYLON.serialize()
  42947. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  42948. __decorate([
  42949. BABYLON.serialize()
  42950. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  42951. __decorate([
  42952. BABYLON.serialize()
  42953. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  42954. return ArcRotateCamera;
  42955. }(BABYLON.TargetCamera));
  42956. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42957. })(BABYLON || (BABYLON = {}));
  42958. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42959. var BABYLON;
  42960. (function (BABYLON) {
  42961. /**
  42962. * The HemisphericLight simulates the ambient environment light,
  42963. * so the passed direction is the light reflection direction, not the incoming direction.
  42964. */
  42965. var HemisphericLight = /** @class */ (function (_super) {
  42966. __extends(HemisphericLight, _super);
  42967. /**
  42968. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42969. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42970. * The HemisphericLight can't cast shadows.
  42971. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42972. * @param name The friendly name of the light
  42973. * @param direction The direction of the light reflection
  42974. * @param scene The scene the light belongs to
  42975. */
  42976. function HemisphericLight(name, direction, scene) {
  42977. var _this = _super.call(this, name, scene) || this;
  42978. /**
  42979. * The groundColor is the light in the opposite direction to the one specified during creation.
  42980. * 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.
  42981. */
  42982. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42983. _this.direction = direction || BABYLON.Vector3.Up();
  42984. return _this;
  42985. }
  42986. HemisphericLight.prototype._buildUniformLayout = function () {
  42987. this._uniformBuffer.addUniform("vLightData", 4);
  42988. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42989. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42990. this._uniformBuffer.addUniform("vLightGround", 3);
  42991. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42992. this._uniformBuffer.addUniform("depthValues", 2);
  42993. this._uniformBuffer.create();
  42994. };
  42995. /**
  42996. * Returns the string "HemisphericLight".
  42997. * @return The class name
  42998. */
  42999. HemisphericLight.prototype.getClassName = function () {
  43000. return "HemisphericLight";
  43001. };
  43002. /**
  43003. * Sets the HemisphericLight direction towards the passed target (Vector3).
  43004. * Returns the updated direction.
  43005. * @param target The target the direction should point to
  43006. * @return The computed direction
  43007. */
  43008. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  43009. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  43010. return this.direction;
  43011. };
  43012. /**
  43013. * Returns the shadow generator associated to the light.
  43014. * @returns Always null for hemispheric lights because it does not support shadows.
  43015. */
  43016. HemisphericLight.prototype.getShadowGenerator = function () {
  43017. return null;
  43018. };
  43019. /**
  43020. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  43021. * @param effect The effect to update
  43022. * @param lightIndex The index of the light in the effect to update
  43023. * @returns The hemispheric light
  43024. */
  43025. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  43026. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  43027. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  43028. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  43029. return this;
  43030. };
  43031. /**
  43032. * @ignore internal use only.
  43033. */
  43034. HemisphericLight.prototype._getWorldMatrix = function () {
  43035. if (!this._worldMatrix) {
  43036. this._worldMatrix = BABYLON.Matrix.Identity();
  43037. }
  43038. return this._worldMatrix;
  43039. };
  43040. /**
  43041. * Returns the integer 3.
  43042. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43043. */
  43044. HemisphericLight.prototype.getTypeID = function () {
  43045. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  43046. };
  43047. __decorate([
  43048. BABYLON.serializeAsColor3()
  43049. ], HemisphericLight.prototype, "groundColor", void 0);
  43050. __decorate([
  43051. BABYLON.serializeAsVector3()
  43052. ], HemisphericLight.prototype, "direction", void 0);
  43053. return HemisphericLight;
  43054. }(BABYLON.Light));
  43055. BABYLON.HemisphericLight = HemisphericLight;
  43056. })(BABYLON || (BABYLON = {}));
  43057. //# sourceMappingURL=babylon.hemisphericLight.js.map
  43058. var BABYLON;
  43059. (function (BABYLON) {
  43060. /**
  43061. * Base implementation of @see IShadowLight
  43062. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  43063. */
  43064. var ShadowLight = /** @class */ (function (_super) {
  43065. __extends(ShadowLight, _super);
  43066. function ShadowLight() {
  43067. var _this = _super !== null && _super.apply(this, arguments) || this;
  43068. _this._needProjectionMatrixCompute = true;
  43069. return _this;
  43070. }
  43071. ShadowLight.prototype._setPosition = function (value) {
  43072. this._position = value;
  43073. };
  43074. Object.defineProperty(ShadowLight.prototype, "position", {
  43075. /**
  43076. * Sets the position the shadow will be casted from. Also use as the light position for both
  43077. * point and spot lights.
  43078. */
  43079. get: function () {
  43080. return this._position;
  43081. },
  43082. /**
  43083. * Sets the position the shadow will be casted from. Also use as the light position for both
  43084. * point and spot lights.
  43085. */
  43086. set: function (value) {
  43087. this._setPosition(value);
  43088. },
  43089. enumerable: true,
  43090. configurable: true
  43091. });
  43092. ShadowLight.prototype._setDirection = function (value) {
  43093. this._direction = value;
  43094. };
  43095. Object.defineProperty(ShadowLight.prototype, "direction", {
  43096. /**
  43097. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  43098. * Also use as the light direction on spot and directional lights.
  43099. */
  43100. get: function () {
  43101. return this._direction;
  43102. },
  43103. /**
  43104. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  43105. * Also use as the light direction on spot and directional lights.
  43106. */
  43107. set: function (value) {
  43108. this._setDirection(value);
  43109. },
  43110. enumerable: true,
  43111. configurable: true
  43112. });
  43113. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  43114. /**
  43115. * Gets the shadow projection clipping minimum z value.
  43116. */
  43117. get: function () {
  43118. return this._shadowMinZ;
  43119. },
  43120. /**
  43121. * Sets the shadow projection clipping minimum z value.
  43122. */
  43123. set: function (value) {
  43124. this._shadowMinZ = value;
  43125. this.forceProjectionMatrixCompute();
  43126. },
  43127. enumerable: true,
  43128. configurable: true
  43129. });
  43130. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  43131. /**
  43132. * Sets the shadow projection clipping maximum z value.
  43133. */
  43134. get: function () {
  43135. return this._shadowMaxZ;
  43136. },
  43137. /**
  43138. * Gets the shadow projection clipping maximum z value.
  43139. */
  43140. set: function (value) {
  43141. this._shadowMaxZ = value;
  43142. this.forceProjectionMatrixCompute();
  43143. },
  43144. enumerable: true,
  43145. configurable: true
  43146. });
  43147. /**
  43148. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  43149. * @returns true if the information has been computed, false if it does not need to (no parenting)
  43150. */
  43151. ShadowLight.prototype.computeTransformedInformation = function () {
  43152. if (this.parent && this.parent.getWorldMatrix) {
  43153. if (!this.transformedPosition) {
  43154. this.transformedPosition = BABYLON.Vector3.Zero();
  43155. }
  43156. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  43157. // In case the direction is present.
  43158. if (this.direction) {
  43159. if (!this.transformedDirection) {
  43160. this.transformedDirection = BABYLON.Vector3.Zero();
  43161. }
  43162. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  43163. }
  43164. return true;
  43165. }
  43166. return false;
  43167. };
  43168. /**
  43169. * Return the depth scale used for the shadow map.
  43170. * @returns the depth scale.
  43171. */
  43172. ShadowLight.prototype.getDepthScale = function () {
  43173. return 50.0;
  43174. };
  43175. /**
  43176. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  43177. * @param faceIndex The index of the face we are computed the direction to generate shadow
  43178. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  43179. */
  43180. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  43181. return this.transformedDirection ? this.transformedDirection : this.direction;
  43182. };
  43183. /**
  43184. * Returns the ShadowLight absolute position in the World.
  43185. * @returns the position vector in world space
  43186. */
  43187. ShadowLight.prototype.getAbsolutePosition = function () {
  43188. return this.transformedPosition ? this.transformedPosition : this.position;
  43189. };
  43190. /**
  43191. * Sets the ShadowLight direction toward the passed target.
  43192. * @param target The point tot target in local space
  43193. * @returns the updated ShadowLight direction
  43194. */
  43195. ShadowLight.prototype.setDirectionToTarget = function (target) {
  43196. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  43197. return this.direction;
  43198. };
  43199. /**
  43200. * Returns the light rotation in euler definition.
  43201. * @returns the x y z rotation in local space.
  43202. */
  43203. ShadowLight.prototype.getRotation = function () {
  43204. this.direction.normalize();
  43205. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  43206. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  43207. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  43208. };
  43209. /**
  43210. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  43211. * @returns true if a cube texture needs to be use
  43212. */
  43213. ShadowLight.prototype.needCube = function () {
  43214. return false;
  43215. };
  43216. /**
  43217. * Detects if the projection matrix requires to be recomputed this frame.
  43218. * @returns true if it requires to be recomputed otherwise, false.
  43219. */
  43220. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  43221. return this._needProjectionMatrixCompute;
  43222. };
  43223. /**
  43224. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  43225. */
  43226. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  43227. this._needProjectionMatrixCompute = true;
  43228. };
  43229. /**
  43230. * Get the world matrix of the sahdow lights.
  43231. * @ignore Internal Use Only
  43232. */
  43233. ShadowLight.prototype._getWorldMatrix = function () {
  43234. if (!this._worldMatrix) {
  43235. this._worldMatrix = BABYLON.Matrix.Identity();
  43236. }
  43237. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  43238. return this._worldMatrix;
  43239. };
  43240. /**
  43241. * Gets the minZ used for shadow according to both the scene and the light.
  43242. * @param activeCamera The camera we are returning the min for
  43243. * @returns the depth min z
  43244. */
  43245. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  43246. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  43247. };
  43248. /**
  43249. * Gets the maxZ used for shadow according to both the scene and the light.
  43250. * @param activeCamera The camera we are returning the max for
  43251. * @returns the depth max z
  43252. */
  43253. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  43254. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  43255. };
  43256. /**
  43257. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  43258. * @param matrix The materix to updated with the projection information
  43259. * @param viewMatrix The transform matrix of the light
  43260. * @param renderList The list of mesh to render in the map
  43261. * @returns The current light
  43262. */
  43263. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43264. if (this.customProjectionMatrixBuilder) {
  43265. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  43266. }
  43267. else {
  43268. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43269. }
  43270. return this;
  43271. };
  43272. __decorate([
  43273. BABYLON.serializeAsVector3()
  43274. ], ShadowLight.prototype, "position", null);
  43275. __decorate([
  43276. BABYLON.serializeAsVector3()
  43277. ], ShadowLight.prototype, "direction", null);
  43278. __decorate([
  43279. BABYLON.serialize()
  43280. ], ShadowLight.prototype, "shadowMinZ", null);
  43281. __decorate([
  43282. BABYLON.serialize()
  43283. ], ShadowLight.prototype, "shadowMaxZ", null);
  43284. return ShadowLight;
  43285. }(BABYLON.Light));
  43286. BABYLON.ShadowLight = ShadowLight;
  43287. })(BABYLON || (BABYLON = {}));
  43288. //# sourceMappingURL=babylon.shadowLight.js.map
  43289. var BABYLON;
  43290. (function (BABYLON) {
  43291. /**
  43292. * A point light is a light defined by an unique point in world space.
  43293. * The light is emitted in every direction from this point.
  43294. * A good example of a point light is a standard light bulb.
  43295. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43296. */
  43297. var PointLight = /** @class */ (function (_super) {
  43298. __extends(PointLight, _super);
  43299. /**
  43300. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  43301. * A PointLight emits the light in every direction.
  43302. * It can cast shadows.
  43303. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  43304. * ```javascript
  43305. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  43306. * ```
  43307. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43308. * @param name The light friendly name
  43309. * @param position The position of the point light in the scene
  43310. * @param scene The scene the lights belongs to
  43311. */
  43312. function PointLight(name, position, scene) {
  43313. var _this = _super.call(this, name, scene) || this;
  43314. _this._shadowAngle = Math.PI / 2;
  43315. _this.position = position;
  43316. return _this;
  43317. }
  43318. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  43319. /**
  43320. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43321. * This specifies what angle the shadow will use to be created.
  43322. *
  43323. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43324. */
  43325. get: function () {
  43326. return this._shadowAngle;
  43327. },
  43328. /**
  43329. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43330. * This specifies what angle the shadow will use to be created.
  43331. *
  43332. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43333. */
  43334. set: function (value) {
  43335. this._shadowAngle = value;
  43336. this.forceProjectionMatrixCompute();
  43337. },
  43338. enumerable: true,
  43339. configurable: true
  43340. });
  43341. Object.defineProperty(PointLight.prototype, "direction", {
  43342. /**
  43343. * Gets the direction if it has been set.
  43344. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43345. */
  43346. get: function () {
  43347. return this._direction;
  43348. },
  43349. /**
  43350. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43351. */
  43352. set: function (value) {
  43353. var previousNeedCube = this.needCube();
  43354. this._direction = value;
  43355. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  43356. this._shadowGenerator.recreateShadowMap();
  43357. }
  43358. },
  43359. enumerable: true,
  43360. configurable: true
  43361. });
  43362. /**
  43363. * Returns the string "PointLight"
  43364. * @returns the class name
  43365. */
  43366. PointLight.prototype.getClassName = function () {
  43367. return "PointLight";
  43368. };
  43369. /**
  43370. * Returns the integer 0.
  43371. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43372. */
  43373. PointLight.prototype.getTypeID = function () {
  43374. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  43375. };
  43376. /**
  43377. * Specifies wether or not the shadowmap should be a cube texture.
  43378. * @returns true if the shadowmap needs to be a cube texture.
  43379. */
  43380. PointLight.prototype.needCube = function () {
  43381. return !this.direction;
  43382. };
  43383. /**
  43384. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  43385. * @param faceIndex The index of the face we are computed the direction to generate shadow
  43386. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  43387. */
  43388. PointLight.prototype.getShadowDirection = function (faceIndex) {
  43389. if (this.direction) {
  43390. return _super.prototype.getShadowDirection.call(this, faceIndex);
  43391. }
  43392. else {
  43393. switch (faceIndex) {
  43394. case 0:
  43395. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  43396. case 1:
  43397. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  43398. case 2:
  43399. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  43400. case 3:
  43401. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  43402. case 4:
  43403. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  43404. case 5:
  43405. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  43406. }
  43407. }
  43408. return BABYLON.Vector3.Zero();
  43409. };
  43410. /**
  43411. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  43412. * - fov = PI / 2
  43413. * - aspect ratio : 1.0
  43414. * - z-near and far equal to the active camera minZ and maxZ.
  43415. * Returns the PointLight.
  43416. */
  43417. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43418. var activeCamera = this.getScene().activeCamera;
  43419. if (!activeCamera) {
  43420. return;
  43421. }
  43422. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43423. };
  43424. PointLight.prototype._buildUniformLayout = function () {
  43425. this._uniformBuffer.addUniform("vLightData", 4);
  43426. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43427. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43428. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43429. this._uniformBuffer.addUniform("depthValues", 2);
  43430. this._uniformBuffer.create();
  43431. };
  43432. /**
  43433. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  43434. * @param effect The effect to update
  43435. * @param lightIndex The index of the light in the effect to update
  43436. * @returns The point light
  43437. */
  43438. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  43439. if (this.computeTransformedInformation()) {
  43440. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  43441. return this;
  43442. }
  43443. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  43444. return this;
  43445. };
  43446. __decorate([
  43447. BABYLON.serialize()
  43448. ], PointLight.prototype, "shadowAngle", null);
  43449. return PointLight;
  43450. }(BABYLON.ShadowLight));
  43451. BABYLON.PointLight = PointLight;
  43452. })(BABYLON || (BABYLON = {}));
  43453. //# sourceMappingURL=babylon.pointLight.js.map
  43454. var BABYLON;
  43455. (function (BABYLON) {
  43456. /**
  43457. * A directional light is defined by a direction (what a surprise!).
  43458. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  43459. * 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.
  43460. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43461. */
  43462. var DirectionalLight = /** @class */ (function (_super) {
  43463. __extends(DirectionalLight, _super);
  43464. /**
  43465. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  43466. * The directional light is emitted from everywhere in the given direction.
  43467. * It can cast shawdows.
  43468. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43469. * @param name The friendly name of the light
  43470. * @param direction The direction of the light
  43471. * @param scene The scene the light belongs to
  43472. */
  43473. function DirectionalLight(name, direction, scene) {
  43474. var _this = _super.call(this, name, scene) || this;
  43475. _this._shadowFrustumSize = 0;
  43476. _this._shadowOrthoScale = 0.5;
  43477. /**
  43478. * Automatically compute the projection matrix to best fit (including all the casters)
  43479. * on each frame.
  43480. */
  43481. _this.autoUpdateExtends = true;
  43482. // Cache
  43483. _this._orthoLeft = Number.MAX_VALUE;
  43484. _this._orthoRight = Number.MIN_VALUE;
  43485. _this._orthoTop = Number.MIN_VALUE;
  43486. _this._orthoBottom = Number.MAX_VALUE;
  43487. _this.position = direction.scale(-1.0);
  43488. _this.direction = direction;
  43489. return _this;
  43490. }
  43491. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  43492. /**
  43493. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  43494. */
  43495. get: function () {
  43496. return this._shadowFrustumSize;
  43497. },
  43498. /**
  43499. * Specifies a fix frustum size for the shadow generation.
  43500. */
  43501. set: function (value) {
  43502. this._shadowFrustumSize = value;
  43503. this.forceProjectionMatrixCompute();
  43504. },
  43505. enumerable: true,
  43506. configurable: true
  43507. });
  43508. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  43509. /**
  43510. * Gets the shadow projection scale against the optimal computed one.
  43511. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43512. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43513. */
  43514. get: function () {
  43515. return this._shadowOrthoScale;
  43516. },
  43517. /**
  43518. * Sets the shadow projection scale against the optimal computed one.
  43519. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43520. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43521. */
  43522. set: function (value) {
  43523. this._shadowOrthoScale = value;
  43524. this.forceProjectionMatrixCompute();
  43525. },
  43526. enumerable: true,
  43527. configurable: true
  43528. });
  43529. /**
  43530. * Returns the string "DirectionalLight".
  43531. * @return The class name
  43532. */
  43533. DirectionalLight.prototype.getClassName = function () {
  43534. return "DirectionalLight";
  43535. };
  43536. /**
  43537. * Returns the integer 1.
  43538. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43539. */
  43540. DirectionalLight.prototype.getTypeID = function () {
  43541. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  43542. };
  43543. /**
  43544. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  43545. * Returns the DirectionalLight Shadow projection matrix.
  43546. */
  43547. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43548. if (this.shadowFrustumSize > 0) {
  43549. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  43550. }
  43551. else {
  43552. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43553. }
  43554. };
  43555. /**
  43556. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  43557. * Returns the DirectionalLight Shadow projection matrix.
  43558. */
  43559. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  43560. var activeCamera = this.getScene().activeCamera;
  43561. if (!activeCamera) {
  43562. return;
  43563. }
  43564. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  43565. };
  43566. /**
  43567. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  43568. * Returns the DirectionalLight Shadow projection matrix.
  43569. */
  43570. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43571. var activeCamera = this.getScene().activeCamera;
  43572. if (!activeCamera) {
  43573. return;
  43574. }
  43575. // Check extends
  43576. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  43577. var tempVector3 = BABYLON.Vector3.Zero();
  43578. this._orthoLeft = Number.MAX_VALUE;
  43579. this._orthoRight = Number.MIN_VALUE;
  43580. this._orthoTop = Number.MIN_VALUE;
  43581. this._orthoBottom = Number.MAX_VALUE;
  43582. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  43583. var mesh = renderList[meshIndex];
  43584. if (!mesh) {
  43585. continue;
  43586. }
  43587. var boundingInfo = mesh.getBoundingInfo();
  43588. var boundingBox = boundingInfo.boundingBox;
  43589. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  43590. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  43591. if (tempVector3.x < this._orthoLeft)
  43592. this._orthoLeft = tempVector3.x;
  43593. if (tempVector3.y < this._orthoBottom)
  43594. this._orthoBottom = tempVector3.y;
  43595. if (tempVector3.x > this._orthoRight)
  43596. this._orthoRight = tempVector3.x;
  43597. if (tempVector3.y > this._orthoTop)
  43598. this._orthoTop = tempVector3.y;
  43599. }
  43600. }
  43601. }
  43602. var xOffset = this._orthoRight - this._orthoLeft;
  43603. var yOffset = this._orthoTop - this._orthoBottom;
  43604. 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);
  43605. };
  43606. DirectionalLight.prototype._buildUniformLayout = function () {
  43607. this._uniformBuffer.addUniform("vLightData", 4);
  43608. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43609. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43610. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43611. this._uniformBuffer.addUniform("depthValues", 2);
  43612. this._uniformBuffer.create();
  43613. };
  43614. /**
  43615. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  43616. * @param effect The effect to update
  43617. * @param lightIndex The index of the light in the effect to update
  43618. * @returns The directional light
  43619. */
  43620. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  43621. if (this.computeTransformedInformation()) {
  43622. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  43623. return this;
  43624. }
  43625. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  43626. return this;
  43627. };
  43628. /**
  43629. * Gets the minZ used for shadow according to both the scene and the light.
  43630. *
  43631. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43632. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43633. * @param activeCamera The camera we are returning the min for
  43634. * @returns the depth min z
  43635. */
  43636. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  43637. return 1;
  43638. };
  43639. /**
  43640. * Gets the maxZ used for shadow according to both the scene and the light.
  43641. *
  43642. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43643. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43644. * @param activeCamera The camera we are returning the max for
  43645. * @returns the depth max z
  43646. */
  43647. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  43648. return 1;
  43649. };
  43650. __decorate([
  43651. BABYLON.serialize()
  43652. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  43653. __decorate([
  43654. BABYLON.serialize()
  43655. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  43656. __decorate([
  43657. BABYLON.serialize()
  43658. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  43659. return DirectionalLight;
  43660. }(BABYLON.ShadowLight));
  43661. BABYLON.DirectionalLight = DirectionalLight;
  43662. })(BABYLON || (BABYLON = {}));
  43663. //# sourceMappingURL=babylon.directionalLight.js.map
  43664. var BABYLON;
  43665. (function (BABYLON) {
  43666. /**
  43667. * A spot light is defined by a position, a direction, an angle, and an exponent.
  43668. * These values define a cone of light starting from the position, emitting toward the direction.
  43669. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  43670. * and the exponent defines the speed of the decay of the light with distance (reach).
  43671. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43672. */
  43673. var SpotLight = /** @class */ (function (_super) {
  43674. __extends(SpotLight, _super);
  43675. /**
  43676. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  43677. * It can cast shadows.
  43678. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43679. * @param name The light friendly name
  43680. * @param position The position of the spot light in the scene
  43681. * @param direction The direction of the light in the scene
  43682. * @param angle The cone angle of the light in Radians
  43683. * @param exponent The light decay speed with the distance from the emission spot
  43684. * @param scene The scene the lights belongs to
  43685. */
  43686. function SpotLight(name, position, direction, angle, exponent, scene) {
  43687. var _this = _super.call(this, name, scene) || this;
  43688. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  43689. _this._projectionTextureLightNear = 1e-6;
  43690. _this._projectionTextureLightFar = 1000.0;
  43691. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  43692. _this._projectionTextureViewLightDirty = true;
  43693. _this._projectionTextureProjectionLightDirty = true;
  43694. _this._projectionTextureDirty = true;
  43695. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  43696. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  43697. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  43698. _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);
  43699. _this.position = position;
  43700. _this.direction = direction;
  43701. _this.angle = angle;
  43702. _this.exponent = exponent;
  43703. return _this;
  43704. }
  43705. Object.defineProperty(SpotLight.prototype, "angle", {
  43706. /**
  43707. * Gets the cone angle of the spot light in Radians.
  43708. */
  43709. get: function () {
  43710. return this._angle;
  43711. },
  43712. /**
  43713. * Sets the cone angle of the spot light in Radians.
  43714. */
  43715. set: function (value) {
  43716. this._angle = value;
  43717. this._projectionTextureProjectionLightDirty = true;
  43718. this.forceProjectionMatrixCompute();
  43719. },
  43720. enumerable: true,
  43721. configurable: true
  43722. });
  43723. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  43724. /**
  43725. * Allows scaling the angle of the light for shadow generation only.
  43726. */
  43727. get: function () {
  43728. return this._shadowAngleScale;
  43729. },
  43730. /**
  43731. * Allows scaling the angle of the light for shadow generation only.
  43732. */
  43733. set: function (value) {
  43734. this._shadowAngleScale = value;
  43735. this.forceProjectionMatrixCompute();
  43736. },
  43737. enumerable: true,
  43738. configurable: true
  43739. });
  43740. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  43741. /**
  43742. * Allows reading the projecton texture
  43743. */
  43744. get: function () {
  43745. return this._projectionTextureMatrix;
  43746. },
  43747. enumerable: true,
  43748. configurable: true
  43749. });
  43750. ;
  43751. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  43752. /**
  43753. * Gets the near clip of the Spotlight for texture projection.
  43754. */
  43755. get: function () {
  43756. return this._projectionTextureLightNear;
  43757. },
  43758. /**
  43759. * Sets the near clip of the Spotlight for texture projection.
  43760. */
  43761. set: function (value) {
  43762. this._projectionTextureLightNear = value;
  43763. this._projectionTextureProjectionLightDirty = true;
  43764. },
  43765. enumerable: true,
  43766. configurable: true
  43767. });
  43768. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  43769. /**
  43770. * Gets the far clip of the Spotlight for texture projection.
  43771. */
  43772. get: function () {
  43773. return this._projectionTextureLightFar;
  43774. },
  43775. /**
  43776. * Sets the far clip of the Spotlight for texture projection.
  43777. */
  43778. set: function (value) {
  43779. this._projectionTextureLightFar = value;
  43780. this._projectionTextureProjectionLightDirty = true;
  43781. },
  43782. enumerable: true,
  43783. configurable: true
  43784. });
  43785. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  43786. /**
  43787. * Gets the Up vector of the Spotlight for texture projection.
  43788. */
  43789. get: function () {
  43790. return this._projectionTextureUpDirection;
  43791. },
  43792. /**
  43793. * Sets the Up vector of the Spotlight for texture projection.
  43794. */
  43795. set: function (value) {
  43796. this._projectionTextureUpDirection = value;
  43797. this._projectionTextureProjectionLightDirty = true;
  43798. },
  43799. enumerable: true,
  43800. configurable: true
  43801. });
  43802. ;
  43803. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  43804. /**
  43805. * Gets the projection texture of the light.
  43806. */
  43807. get: function () {
  43808. return this._projectionTexture;
  43809. },
  43810. /**
  43811. * Sets the projection texture of the light.
  43812. */
  43813. set: function (value) {
  43814. this._projectionTexture = value;
  43815. this._projectionTextureDirty = true;
  43816. },
  43817. enumerable: true,
  43818. configurable: true
  43819. });
  43820. /**
  43821. * Returns the string "SpotLight".
  43822. * @returns the class name
  43823. */
  43824. SpotLight.prototype.getClassName = function () {
  43825. return "SpotLight";
  43826. };
  43827. /**
  43828. * Returns the integer 2.
  43829. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43830. */
  43831. SpotLight.prototype.getTypeID = function () {
  43832. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  43833. };
  43834. /**
  43835. * Overrides the direction setter to recompute the projection texture view light Matrix.
  43836. */
  43837. SpotLight.prototype._setDirection = function (value) {
  43838. _super.prototype._setDirection.call(this, value);
  43839. this._projectionTextureViewLightDirty = true;
  43840. };
  43841. /**
  43842. * Overrides the position setter to recompute the projection texture view light Matrix.
  43843. */
  43844. SpotLight.prototype._setPosition = function (value) {
  43845. _super.prototype._setPosition.call(this, value);
  43846. this._projectionTextureViewLightDirty = true;
  43847. };
  43848. /**
  43849. * 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.
  43850. * Returns the SpotLight.
  43851. */
  43852. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43853. var activeCamera = this.getScene().activeCamera;
  43854. if (!activeCamera) {
  43855. return;
  43856. }
  43857. this._shadowAngleScale = this._shadowAngleScale || 1;
  43858. var angle = this._shadowAngleScale * this._angle;
  43859. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43860. };
  43861. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  43862. this._projectionTextureViewLightDirty = false;
  43863. this._projectionTextureDirty = true;
  43864. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  43865. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  43866. };
  43867. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  43868. this._projectionTextureProjectionLightDirty = false;
  43869. this._projectionTextureDirty = true;
  43870. var light_far = this.projectionTextureLightFar;
  43871. var light_near = this.projectionTextureLightNear;
  43872. var P = light_far / (light_far - light_near);
  43873. var Q = -P * light_near;
  43874. var S = 1.0 / Math.tan(this._angle / 2.0);
  43875. var A = 1.0;
  43876. 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);
  43877. };
  43878. /**
  43879. * Main function for light texture projection matrix computing.
  43880. */
  43881. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  43882. this._projectionTextureDirty = false;
  43883. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  43884. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  43885. };
  43886. SpotLight.prototype._buildUniformLayout = function () {
  43887. this._uniformBuffer.addUniform("vLightData", 4);
  43888. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43889. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43890. this._uniformBuffer.addUniform("vLightDirection", 3);
  43891. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43892. this._uniformBuffer.addUniform("depthValues", 2);
  43893. this._uniformBuffer.create();
  43894. };
  43895. /**
  43896. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  43897. * @param effect The effect to update
  43898. * @param lightIndex The index of the light in the effect to update
  43899. * @returns The spot light
  43900. */
  43901. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  43902. var normalizeDirection;
  43903. if (this.computeTransformedInformation()) {
  43904. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  43905. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  43906. }
  43907. else {
  43908. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  43909. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  43910. }
  43911. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  43912. if (this.projectionTexture && this.projectionTexture.isReady()) {
  43913. if (this._projectionTextureViewLightDirty) {
  43914. this._computeProjectionTextureViewLightMatrix();
  43915. }
  43916. if (this._projectionTextureProjectionLightDirty) {
  43917. this._computeProjectionTextureProjectionLightMatrix();
  43918. }
  43919. if (this._projectionTextureDirty) {
  43920. this._computeProjectionTextureMatrix();
  43921. }
  43922. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  43923. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  43924. }
  43925. return this;
  43926. };
  43927. /**
  43928. * Disposes the light and the associated resources.
  43929. */
  43930. SpotLight.prototype.dispose = function () {
  43931. _super.prototype.dispose.call(this);
  43932. if (this._projectionTexture) {
  43933. this._projectionTexture.dispose();
  43934. }
  43935. };
  43936. __decorate([
  43937. BABYLON.serialize()
  43938. ], SpotLight.prototype, "angle", null);
  43939. __decorate([
  43940. BABYLON.serialize()
  43941. ], SpotLight.prototype, "shadowAngleScale", null);
  43942. __decorate([
  43943. BABYLON.serialize()
  43944. ], SpotLight.prototype, "exponent", void 0);
  43945. __decorate([
  43946. BABYLON.serialize()
  43947. ], SpotLight.prototype, "projectionTextureLightNear", null);
  43948. __decorate([
  43949. BABYLON.serialize()
  43950. ], SpotLight.prototype, "projectionTextureLightFar", null);
  43951. __decorate([
  43952. BABYLON.serialize()
  43953. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  43954. __decorate([
  43955. BABYLON.serializeAsTexture("projectedLightTexture")
  43956. ], SpotLight.prototype, "_projectionTexture", void 0);
  43957. return SpotLight;
  43958. }(BABYLON.ShadowLight));
  43959. BABYLON.SpotLight = SpotLight;
  43960. })(BABYLON || (BABYLON = {}));
  43961. //# sourceMappingURL=babylon.spotLight.js.map
  43962. var BABYLON;
  43963. (function (BABYLON) {
  43964. var AnimationRange = /** @class */ (function () {
  43965. function AnimationRange(name, from, to) {
  43966. this.name = name;
  43967. this.from = from;
  43968. this.to = to;
  43969. }
  43970. AnimationRange.prototype.clone = function () {
  43971. return new AnimationRange(this.name, this.from, this.to);
  43972. };
  43973. return AnimationRange;
  43974. }());
  43975. BABYLON.AnimationRange = AnimationRange;
  43976. /**
  43977. * Composed of a frame, and an action function
  43978. */
  43979. var AnimationEvent = /** @class */ (function () {
  43980. function AnimationEvent(frame, action, onlyOnce) {
  43981. this.frame = frame;
  43982. this.action = action;
  43983. this.onlyOnce = onlyOnce;
  43984. this.isDone = false;
  43985. }
  43986. return AnimationEvent;
  43987. }());
  43988. BABYLON.AnimationEvent = AnimationEvent;
  43989. var PathCursor = /** @class */ (function () {
  43990. function PathCursor(path) {
  43991. this.path = path;
  43992. this._onchange = new Array();
  43993. this.value = 0;
  43994. this.animations = new Array();
  43995. }
  43996. PathCursor.prototype.getPoint = function () {
  43997. var point = this.path.getPointAtLengthPosition(this.value);
  43998. return new BABYLON.Vector3(point.x, 0, point.y);
  43999. };
  44000. PathCursor.prototype.moveAhead = function (step) {
  44001. if (step === void 0) { step = 0.002; }
  44002. this.move(step);
  44003. return this;
  44004. };
  44005. PathCursor.prototype.moveBack = function (step) {
  44006. if (step === void 0) { step = 0.002; }
  44007. this.move(-step);
  44008. return this;
  44009. };
  44010. PathCursor.prototype.move = function (step) {
  44011. if (Math.abs(step) > 1) {
  44012. throw "step size should be less than 1.";
  44013. }
  44014. this.value += step;
  44015. this.ensureLimits();
  44016. this.raiseOnChange();
  44017. return this;
  44018. };
  44019. PathCursor.prototype.ensureLimits = function () {
  44020. while (this.value > 1) {
  44021. this.value -= 1;
  44022. }
  44023. while (this.value < 0) {
  44024. this.value += 1;
  44025. }
  44026. return this;
  44027. };
  44028. // used by animation engine
  44029. PathCursor.prototype.raiseOnChange = function () {
  44030. var _this = this;
  44031. this._onchange.forEach(function (f) { return f(_this); });
  44032. return this;
  44033. };
  44034. PathCursor.prototype.onchange = function (f) {
  44035. this._onchange.push(f);
  44036. return this;
  44037. };
  44038. return PathCursor;
  44039. }());
  44040. BABYLON.PathCursor = PathCursor;
  44041. var AnimationKeyInterpolation;
  44042. (function (AnimationKeyInterpolation) {
  44043. /**
  44044. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  44045. */
  44046. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  44047. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  44048. var Animation = /** @class */ (function () {
  44049. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  44050. this.name = name;
  44051. this.targetProperty = targetProperty;
  44052. this.framePerSecond = framePerSecond;
  44053. this.dataType = dataType;
  44054. this.loopMode = loopMode;
  44055. this.enableBlending = enableBlending;
  44056. this._runtimeAnimations = new Array();
  44057. // The set of event that will be linked to this animation
  44058. this._events = new Array();
  44059. this.blendingSpeed = 0.01;
  44060. this._ranges = {};
  44061. this.targetPropertyPath = targetProperty.split(".");
  44062. this.dataType = dataType;
  44063. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  44064. }
  44065. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  44066. var dataType = undefined;
  44067. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  44068. dataType = Animation.ANIMATIONTYPE_FLOAT;
  44069. }
  44070. else if (from instanceof BABYLON.Quaternion) {
  44071. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  44072. }
  44073. else if (from instanceof BABYLON.Vector3) {
  44074. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  44075. }
  44076. else if (from instanceof BABYLON.Vector2) {
  44077. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  44078. }
  44079. else if (from instanceof BABYLON.Color3) {
  44080. dataType = Animation.ANIMATIONTYPE_COLOR3;
  44081. }
  44082. else if (from instanceof BABYLON.Size) {
  44083. dataType = Animation.ANIMATIONTYPE_SIZE;
  44084. }
  44085. if (dataType == undefined) {
  44086. return null;
  44087. }
  44088. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  44089. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  44090. animation.setKeys(keys);
  44091. if (easingFunction !== undefined) {
  44092. animation.setEasingFunction(easingFunction);
  44093. }
  44094. return animation;
  44095. };
  44096. /**
  44097. * Sets up an animation.
  44098. * @param property the property to animate
  44099. * @param animationType the animation type to apply
  44100. * @param easingFunction the easing function used in the animation
  44101. * @returns The created animation
  44102. */
  44103. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  44104. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  44105. animation.setEasingFunction(easingFunction);
  44106. return animation;
  44107. };
  44108. /**
  44109. * Create and start an animation on a node
  44110. * @param {string} name defines the name of the global animation that will be run on all nodes
  44111. * @param {BABYLON.Node} node defines the root node where the animation will take place
  44112. * @param {string} targetProperty defines property to animate
  44113. * @param {number} framePerSecond defines the number of frame per second yo use
  44114. * @param {number} totalFrame defines the number of frames in total
  44115. * @param {any} from defines the initial value
  44116. * @param {any} to defines the final value
  44117. * @param {number} loopMode defines which loop mode you want to use (off by default)
  44118. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  44119. * @param onAnimationEnd defines the callback to call when animation end
  44120. * @returns the animatable created for this animation
  44121. */
  44122. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  44123. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  44124. if (!animation) {
  44125. return null;
  44126. }
  44127. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  44128. };
  44129. /**
  44130. * Create and start an animation on a node and its descendants
  44131. * @param {string} name defines the name of the global animation that will be run on all nodes
  44132. * @param {BABYLON.Node} node defines the root node where the animation will take place
  44133. * @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.
  44134. * @param {string} targetProperty defines property to animate
  44135. * @param {number} framePerSecond defines the number of frame per second yo use
  44136. * @param {number} totalFrame defines the number of frames in total
  44137. * @param {any} from defines the initial value
  44138. * @param {any} to defines the final value
  44139. * @param {number} loopMode defines which loop mode you want to use (off by default)
  44140. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  44141. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  44142. * @returns the list of animatables created for all nodes
  44143. * @example https://www.babylonjs-playground.com/#MH0VLI
  44144. */
  44145. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  44146. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  44147. if (!animation) {
  44148. return null;
  44149. }
  44150. var scene = node.getScene();
  44151. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  44152. };
  44153. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  44154. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  44155. if (!animation) {
  44156. return null;
  44157. }
  44158. node.animations.push(animation);
  44159. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  44160. };
  44161. /**
  44162. * Transition property of the Camera to the target Value.
  44163. * @param property The property to transition
  44164. * @param targetValue The target Value of the property
  44165. * @param host The object where the property to animate belongs
  44166. * @param scene Scene used to run the animation
  44167. * @param frameRate Framerate (in frame/s) to use
  44168. * @param transition The transition type we want to use
  44169. * @param duration The duration of the animation, in milliseconds
  44170. * @param onAnimationEnd Call back trigger at the end of the animation.
  44171. */
  44172. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  44173. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  44174. if (duration <= 0) {
  44175. host[property] = targetValue;
  44176. if (onAnimationEnd) {
  44177. onAnimationEnd();
  44178. }
  44179. return null;
  44180. }
  44181. var endFrame = frameRate * (duration / 1000);
  44182. transition.setKeys([{
  44183. frame: 0,
  44184. value: host[property].clone ? host[property].clone() : host[property]
  44185. },
  44186. {
  44187. frame: endFrame,
  44188. value: targetValue
  44189. }]);
  44190. if (!host.animations) {
  44191. host.animations = [];
  44192. }
  44193. host.animations.push(transition);
  44194. var animation = scene.beginAnimation(host, 0, endFrame, false);
  44195. animation.onAnimationEnd = onAnimationEnd;
  44196. return animation;
  44197. };
  44198. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  44199. /**
  44200. * Return the array of runtime animations currently using this animation
  44201. */
  44202. get: function () {
  44203. return this._runtimeAnimations;
  44204. },
  44205. enumerable: true,
  44206. configurable: true
  44207. });
  44208. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  44209. get: function () {
  44210. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  44211. var runtimeAnimation = _a[_i];
  44212. if (!runtimeAnimation.isStopped) {
  44213. return true;
  44214. }
  44215. }
  44216. return false;
  44217. },
  44218. enumerable: true,
  44219. configurable: true
  44220. });
  44221. // Methods
  44222. /**
  44223. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  44224. */
  44225. Animation.prototype.toString = function (fullDetails) {
  44226. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  44227. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  44228. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  44229. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  44230. if (fullDetails) {
  44231. ret += ", Ranges: {";
  44232. var first = true;
  44233. for (var name in this._ranges) {
  44234. if (first) {
  44235. ret += ", ";
  44236. first = false;
  44237. }
  44238. ret += name;
  44239. }
  44240. ret += "}";
  44241. }
  44242. return ret;
  44243. };
  44244. /**
  44245. * Add an event to this animation.
  44246. */
  44247. Animation.prototype.addEvent = function (event) {
  44248. this._events.push(event);
  44249. };
  44250. /**
  44251. * Remove all events found at the given frame
  44252. * @param frame
  44253. */
  44254. Animation.prototype.removeEvents = function (frame) {
  44255. for (var index = 0; index < this._events.length; index++) {
  44256. if (this._events[index].frame === frame) {
  44257. this._events.splice(index, 1);
  44258. index--;
  44259. }
  44260. }
  44261. };
  44262. Animation.prototype.getEvents = function () {
  44263. return this._events;
  44264. };
  44265. Animation.prototype.createRange = function (name, from, to) {
  44266. // check name not already in use; could happen for bones after serialized
  44267. if (!this._ranges[name]) {
  44268. this._ranges[name] = new AnimationRange(name, from, to);
  44269. }
  44270. };
  44271. Animation.prototype.deleteRange = function (name, deleteFrames) {
  44272. if (deleteFrames === void 0) { deleteFrames = true; }
  44273. var range = this._ranges[name];
  44274. if (!range) {
  44275. return;
  44276. }
  44277. if (deleteFrames) {
  44278. var from = range.from;
  44279. var to = range.to;
  44280. // this loop MUST go high to low for multiple splices to work
  44281. for (var key = this._keys.length - 1; key >= 0; key--) {
  44282. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  44283. this._keys.splice(key, 1);
  44284. }
  44285. }
  44286. }
  44287. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  44288. };
  44289. Animation.prototype.getRange = function (name) {
  44290. return this._ranges[name];
  44291. };
  44292. Animation.prototype.getKeys = function () {
  44293. return this._keys;
  44294. };
  44295. Animation.prototype.getHighestFrame = function () {
  44296. var ret = 0;
  44297. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  44298. if (ret < this._keys[key].frame) {
  44299. ret = this._keys[key].frame;
  44300. }
  44301. }
  44302. return ret;
  44303. };
  44304. Animation.prototype.getEasingFunction = function () {
  44305. return this._easingFunction;
  44306. };
  44307. Animation.prototype.setEasingFunction = function (easingFunction) {
  44308. this._easingFunction = easingFunction;
  44309. };
  44310. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  44311. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  44312. };
  44313. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44314. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44315. };
  44316. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  44317. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  44318. };
  44319. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44320. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  44321. };
  44322. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  44323. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  44324. };
  44325. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44326. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44327. };
  44328. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  44329. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  44330. };
  44331. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44332. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44333. };
  44334. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  44335. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  44336. };
  44337. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  44338. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  44339. };
  44340. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  44341. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  44342. };
  44343. Animation.prototype.clone = function () {
  44344. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  44345. clone.enableBlending = this.enableBlending;
  44346. clone.blendingSpeed = this.blendingSpeed;
  44347. if (this._keys) {
  44348. clone.setKeys(this._keys);
  44349. }
  44350. if (this._ranges) {
  44351. clone._ranges = {};
  44352. for (var name in this._ranges) {
  44353. var range = this._ranges[name];
  44354. if (!range) {
  44355. continue;
  44356. }
  44357. clone._ranges[name] = range.clone();
  44358. }
  44359. }
  44360. return clone;
  44361. };
  44362. Animation.prototype.setKeys = function (values) {
  44363. this._keys = values.slice(0);
  44364. };
  44365. Animation.prototype.serialize = function () {
  44366. var serializationObject = {};
  44367. serializationObject.name = this.name;
  44368. serializationObject.property = this.targetProperty;
  44369. serializationObject.framePerSecond = this.framePerSecond;
  44370. serializationObject.dataType = this.dataType;
  44371. serializationObject.loopBehavior = this.loopMode;
  44372. serializationObject.enableBlending = this.enableBlending;
  44373. serializationObject.blendingSpeed = this.blendingSpeed;
  44374. var dataType = this.dataType;
  44375. serializationObject.keys = [];
  44376. var keys = this.getKeys();
  44377. for (var index = 0; index < keys.length; index++) {
  44378. var animationKey = keys[index];
  44379. var key = {};
  44380. key.frame = animationKey.frame;
  44381. switch (dataType) {
  44382. case Animation.ANIMATIONTYPE_FLOAT:
  44383. key.values = [animationKey.value];
  44384. break;
  44385. case Animation.ANIMATIONTYPE_QUATERNION:
  44386. case Animation.ANIMATIONTYPE_MATRIX:
  44387. case Animation.ANIMATIONTYPE_VECTOR3:
  44388. case Animation.ANIMATIONTYPE_COLOR3:
  44389. key.values = animationKey.value.asArray();
  44390. break;
  44391. }
  44392. serializationObject.keys.push(key);
  44393. }
  44394. serializationObject.ranges = [];
  44395. for (var name in this._ranges) {
  44396. var source = this._ranges[name];
  44397. if (!source) {
  44398. continue;
  44399. }
  44400. var range = {};
  44401. range.name = name;
  44402. range.from = source.from;
  44403. range.to = source.to;
  44404. serializationObject.ranges.push(range);
  44405. }
  44406. return serializationObject;
  44407. };
  44408. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  44409. get: function () {
  44410. return Animation._ANIMATIONTYPE_FLOAT;
  44411. },
  44412. enumerable: true,
  44413. configurable: true
  44414. });
  44415. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  44416. get: function () {
  44417. return Animation._ANIMATIONTYPE_VECTOR3;
  44418. },
  44419. enumerable: true,
  44420. configurable: true
  44421. });
  44422. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  44423. get: function () {
  44424. return Animation._ANIMATIONTYPE_VECTOR2;
  44425. },
  44426. enumerable: true,
  44427. configurable: true
  44428. });
  44429. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  44430. get: function () {
  44431. return Animation._ANIMATIONTYPE_SIZE;
  44432. },
  44433. enumerable: true,
  44434. configurable: true
  44435. });
  44436. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  44437. get: function () {
  44438. return Animation._ANIMATIONTYPE_QUATERNION;
  44439. },
  44440. enumerable: true,
  44441. configurable: true
  44442. });
  44443. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  44444. get: function () {
  44445. return Animation._ANIMATIONTYPE_MATRIX;
  44446. },
  44447. enumerable: true,
  44448. configurable: true
  44449. });
  44450. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  44451. get: function () {
  44452. return Animation._ANIMATIONTYPE_COLOR3;
  44453. },
  44454. enumerable: true,
  44455. configurable: true
  44456. });
  44457. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  44458. get: function () {
  44459. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  44460. },
  44461. enumerable: true,
  44462. configurable: true
  44463. });
  44464. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  44465. get: function () {
  44466. return Animation._ANIMATIONLOOPMODE_CYCLE;
  44467. },
  44468. enumerable: true,
  44469. configurable: true
  44470. });
  44471. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  44472. get: function () {
  44473. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  44474. },
  44475. enumerable: true,
  44476. configurable: true
  44477. });
  44478. Animation.Parse = function (parsedAnimation) {
  44479. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  44480. var dataType = parsedAnimation.dataType;
  44481. var keys = [];
  44482. var data;
  44483. var index;
  44484. if (parsedAnimation.enableBlending) {
  44485. animation.enableBlending = parsedAnimation.enableBlending;
  44486. }
  44487. if (parsedAnimation.blendingSpeed) {
  44488. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  44489. }
  44490. for (index = 0; index < parsedAnimation.keys.length; index++) {
  44491. var key = parsedAnimation.keys[index];
  44492. var inTangent;
  44493. var outTangent;
  44494. switch (dataType) {
  44495. case Animation.ANIMATIONTYPE_FLOAT:
  44496. data = key.values[0];
  44497. if (key.values.length >= 1) {
  44498. inTangent = key.values[1];
  44499. }
  44500. if (key.values.length >= 2) {
  44501. outTangent = key.values[2];
  44502. }
  44503. break;
  44504. case Animation.ANIMATIONTYPE_QUATERNION:
  44505. data = BABYLON.Quaternion.FromArray(key.values);
  44506. if (key.values.length >= 8) {
  44507. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  44508. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  44509. inTangent = _inTangent;
  44510. }
  44511. }
  44512. if (key.values.length >= 12) {
  44513. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  44514. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  44515. outTangent = _outTangent;
  44516. }
  44517. }
  44518. break;
  44519. case Animation.ANIMATIONTYPE_MATRIX:
  44520. data = BABYLON.Matrix.FromArray(key.values);
  44521. break;
  44522. case Animation.ANIMATIONTYPE_COLOR3:
  44523. data = BABYLON.Color3.FromArray(key.values);
  44524. break;
  44525. case Animation.ANIMATIONTYPE_VECTOR3:
  44526. default:
  44527. data = BABYLON.Vector3.FromArray(key.values);
  44528. break;
  44529. }
  44530. var keyData = {};
  44531. keyData.frame = key.frame;
  44532. keyData.value = data;
  44533. if (inTangent != undefined) {
  44534. keyData.inTangent = inTangent;
  44535. }
  44536. if (outTangent != undefined) {
  44537. keyData.outTangent = outTangent;
  44538. }
  44539. keys.push(keyData);
  44540. }
  44541. animation.setKeys(keys);
  44542. if (parsedAnimation.ranges) {
  44543. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  44544. data = parsedAnimation.ranges[index];
  44545. animation.createRange(data.name, data.from, data.to);
  44546. }
  44547. }
  44548. return animation;
  44549. };
  44550. Animation.AppendSerializedAnimations = function (source, destination) {
  44551. if (source.animations) {
  44552. destination.animations = [];
  44553. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  44554. var animation = source.animations[animationIndex];
  44555. destination.animations.push(animation.serialize());
  44556. }
  44557. }
  44558. };
  44559. Animation.AllowMatricesInterpolation = false;
  44560. // Statics
  44561. Animation._ANIMATIONTYPE_FLOAT = 0;
  44562. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  44563. Animation._ANIMATIONTYPE_QUATERNION = 2;
  44564. Animation._ANIMATIONTYPE_MATRIX = 3;
  44565. Animation._ANIMATIONTYPE_COLOR3 = 4;
  44566. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  44567. Animation._ANIMATIONTYPE_SIZE = 6;
  44568. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  44569. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  44570. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  44571. return Animation;
  44572. }());
  44573. BABYLON.Animation = Animation;
  44574. })(BABYLON || (BABYLON = {}));
  44575. //# sourceMappingURL=babylon.animation.js.map
  44576. var BABYLON;
  44577. (function (BABYLON) {
  44578. /**
  44579. * This class defines the direct association between an animation and a target
  44580. */
  44581. var TargetedAnimation = /** @class */ (function () {
  44582. function TargetedAnimation() {
  44583. }
  44584. return TargetedAnimation;
  44585. }());
  44586. BABYLON.TargetedAnimation = TargetedAnimation;
  44587. /**
  44588. * Use this class to create coordinated animations on multiple targets
  44589. */
  44590. var AnimationGroup = /** @class */ (function () {
  44591. function AnimationGroup(name, scene) {
  44592. if (scene === void 0) { scene = null; }
  44593. this.name = name;
  44594. this._targetedAnimations = new Array();
  44595. this._animatables = new Array();
  44596. this._from = Number.MAX_VALUE;
  44597. this._to = -Number.MAX_VALUE;
  44598. this._speedRatio = 1;
  44599. this.onAnimationEndObservable = new BABYLON.Observable();
  44600. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44601. this._scene.animationGroups.push(this);
  44602. }
  44603. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  44604. /**
  44605. * Define if the animations are started
  44606. */
  44607. get: function () {
  44608. return this._isStarted;
  44609. },
  44610. enumerable: true,
  44611. configurable: true
  44612. });
  44613. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  44614. /**
  44615. * Gets or sets the speed ratio to use for all animations
  44616. */
  44617. get: function () {
  44618. return this._speedRatio;
  44619. },
  44620. /**
  44621. * Gets or sets the speed ratio to use for all animations
  44622. */
  44623. set: function (value) {
  44624. if (this._speedRatio === value) {
  44625. return;
  44626. }
  44627. this._speedRatio = value;
  44628. for (var index = 0; index < this._animatables.length; index++) {
  44629. var animatable = this._animatables[index];
  44630. animatable.speedRatio = this._speedRatio;
  44631. }
  44632. },
  44633. enumerable: true,
  44634. configurable: true
  44635. });
  44636. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  44637. /**
  44638. * Gets the targeted animations for this animation group
  44639. */
  44640. get: function () {
  44641. return this._targetedAnimations;
  44642. },
  44643. enumerable: true,
  44644. configurable: true
  44645. });
  44646. /**
  44647. * Add an animation (with its target) in the group
  44648. * @param animation defines the animation we want to add
  44649. * @param target defines the target of the animation
  44650. * @returns the {BABYLON.TargetedAnimation} object
  44651. */
  44652. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  44653. var targetedAnimation = {
  44654. animation: animation,
  44655. target: target
  44656. };
  44657. var keys = animation.getKeys();
  44658. if (this._from > keys[0].frame) {
  44659. this._from = keys[0].frame;
  44660. }
  44661. if (this._to < keys[keys.length - 1].frame) {
  44662. this._to = keys[keys.length - 1].frame;
  44663. }
  44664. this._targetedAnimations.push(targetedAnimation);
  44665. return targetedAnimation;
  44666. };
  44667. /**
  44668. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  44669. * It can add constant keys at begin or end
  44670. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  44671. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  44672. */
  44673. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  44674. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  44675. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  44676. beginFrame = Math.max(beginFrame, this._from);
  44677. endFrame = Math.min(endFrame, this._to);
  44678. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44679. var targetedAnimation = this._targetedAnimations[index];
  44680. var keys = targetedAnimation.animation.getKeys();
  44681. var startKey = keys[0];
  44682. var endKey = keys[keys.length - 1];
  44683. if (startKey.frame > beginFrame) {
  44684. var newKey = {
  44685. frame: beginFrame,
  44686. value: startKey.value,
  44687. inTangent: startKey.inTangent,
  44688. outTangent: startKey.outTangent,
  44689. interpolation: startKey.interpolation
  44690. };
  44691. keys.splice(0, 0, newKey);
  44692. }
  44693. if (endKey.frame < endFrame) {
  44694. var newKey = {
  44695. frame: endFrame,
  44696. value: endKey.value,
  44697. inTangent: endKey.outTangent,
  44698. outTangent: endKey.outTangent,
  44699. interpolation: endKey.interpolation
  44700. };
  44701. keys.push(newKey);
  44702. }
  44703. }
  44704. return this;
  44705. };
  44706. /**
  44707. * Start all animations on given targets
  44708. * @param loop defines if animations must loop
  44709. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  44710. */
  44711. AnimationGroup.prototype.start = function (loop, speedRatio) {
  44712. var _this = this;
  44713. if (loop === void 0) { loop = false; }
  44714. if (speedRatio === void 0) { speedRatio = 1; }
  44715. if (this._isStarted || this._targetedAnimations.length === 0) {
  44716. return this;
  44717. }
  44718. var _loop_1 = function () {
  44719. var targetedAnimation = this_1._targetedAnimations[index];
  44720. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  44721. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  44722. }));
  44723. };
  44724. var this_1 = this;
  44725. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44726. _loop_1();
  44727. }
  44728. this._speedRatio = speedRatio;
  44729. this._isStarted = true;
  44730. return this;
  44731. };
  44732. /**
  44733. * Pause all animations
  44734. */
  44735. AnimationGroup.prototype.pause = function () {
  44736. if (!this._isStarted) {
  44737. return this;
  44738. }
  44739. for (var index = 0; index < this._animatables.length; index++) {
  44740. var animatable = this._animatables[index];
  44741. animatable.pause();
  44742. }
  44743. return this;
  44744. };
  44745. /**
  44746. * Play all animations to initial state
  44747. * This function will start() the animations if they were not started or will restart() them if they were paused
  44748. * @param loop defines if animations must loop
  44749. */
  44750. AnimationGroup.prototype.play = function (loop) {
  44751. if (this.isStarted) {
  44752. if (loop !== undefined) {
  44753. for (var index = 0; index < this._animatables.length; index++) {
  44754. var animatable = this._animatables[index];
  44755. animatable.loopAnimation = loop;
  44756. }
  44757. }
  44758. this.restart();
  44759. }
  44760. else {
  44761. this.start(loop, this._speedRatio);
  44762. }
  44763. return this;
  44764. };
  44765. /**
  44766. * Reset all animations to initial state
  44767. */
  44768. AnimationGroup.prototype.reset = function () {
  44769. if (!this._isStarted) {
  44770. return this;
  44771. }
  44772. for (var index = 0; index < this._animatables.length; index++) {
  44773. var animatable = this._animatables[index];
  44774. animatable.reset();
  44775. }
  44776. return this;
  44777. };
  44778. /**
  44779. * Restart animations from key 0
  44780. */
  44781. AnimationGroup.prototype.restart = function () {
  44782. if (!this._isStarted) {
  44783. return this;
  44784. }
  44785. for (var index = 0; index < this._animatables.length; index++) {
  44786. var animatable = this._animatables[index];
  44787. animatable.restart();
  44788. }
  44789. return this;
  44790. };
  44791. /**
  44792. * Stop all animations
  44793. */
  44794. AnimationGroup.prototype.stop = function () {
  44795. if (!this._isStarted) {
  44796. return this;
  44797. }
  44798. for (var index = 0; index < this._animatables.length; index++) {
  44799. var animatable = this._animatables[index];
  44800. animatable.stop();
  44801. }
  44802. this._isStarted = false;
  44803. return this;
  44804. };
  44805. /**
  44806. * Dispose all associated resources
  44807. */
  44808. AnimationGroup.prototype.dispose = function () {
  44809. this._targetedAnimations = [];
  44810. this._animatables = [];
  44811. var index = this._scene.animationGroups.indexOf(this);
  44812. if (index > -1) {
  44813. this._scene.animationGroups.splice(index, 1);
  44814. }
  44815. };
  44816. return AnimationGroup;
  44817. }());
  44818. BABYLON.AnimationGroup = AnimationGroup;
  44819. })(BABYLON || (BABYLON = {}));
  44820. //# sourceMappingURL=babylon.animationGroup.js.map
  44821. var BABYLON;
  44822. (function (BABYLON) {
  44823. var RuntimeAnimation = /** @class */ (function () {
  44824. function RuntimeAnimation(target, animation) {
  44825. this._offsetsCache = {};
  44826. this._highLimitsCache = {};
  44827. this._stopped = false;
  44828. this._blendingFactor = 0;
  44829. this._ratioOffset = 0;
  44830. this._animation = animation;
  44831. this._target = target;
  44832. animation._runtimeAnimations.push(this);
  44833. }
  44834. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  44835. get: function () {
  44836. return this._animation;
  44837. },
  44838. enumerable: true,
  44839. configurable: true
  44840. });
  44841. RuntimeAnimation.prototype.reset = function () {
  44842. this._offsetsCache = {};
  44843. this._highLimitsCache = {};
  44844. this.currentFrame = 0;
  44845. this._blendingFactor = 0;
  44846. this._originalBlendValue = null;
  44847. };
  44848. RuntimeAnimation.prototype.isStopped = function () {
  44849. return this._stopped;
  44850. };
  44851. RuntimeAnimation.prototype.dispose = function () {
  44852. var index = this._animation.runtimeAnimations.indexOf(this);
  44853. if (index > -1) {
  44854. this._animation.runtimeAnimations.splice(index, 1);
  44855. }
  44856. };
  44857. RuntimeAnimation.prototype._getKeyValue = function (value) {
  44858. if (typeof value === "function") {
  44859. return value();
  44860. }
  44861. return value;
  44862. };
  44863. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  44864. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  44865. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  44866. }
  44867. this.currentFrame = currentFrame;
  44868. var keys = this._animation.getKeys();
  44869. // Try to get a hash to find the right key
  44870. 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));
  44871. if (keys[startKeyIndex].frame >= currentFrame) {
  44872. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  44873. startKeyIndex--;
  44874. }
  44875. }
  44876. for (var key = startKeyIndex; key < keys.length; key++) {
  44877. var endKey = keys[key + 1];
  44878. if (endKey.frame >= currentFrame) {
  44879. var startKey = keys[key];
  44880. var startValue = this._getKeyValue(startKey.value);
  44881. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  44882. return startValue;
  44883. }
  44884. var endValue = this._getKeyValue(endKey.value);
  44885. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  44886. var frameDelta = endKey.frame - startKey.frame;
  44887. // gradient : percent of currentFrame between the frame inf and the frame sup
  44888. var gradient = (currentFrame - startKey.frame) / frameDelta;
  44889. // check for easingFunction and correction of gradient
  44890. var easingFunction = this._animation.getEasingFunction();
  44891. if (easingFunction != null) {
  44892. gradient = easingFunction.ease(gradient);
  44893. }
  44894. switch (this._animation.dataType) {
  44895. // Float
  44896. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44897. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  44898. switch (loopMode) {
  44899. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44900. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44901. return floatValue;
  44902. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44903. return offsetValue * repeatCount + floatValue;
  44904. }
  44905. break;
  44906. // Quaternion
  44907. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44908. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  44909. switch (loopMode) {
  44910. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44911. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44912. return quatValue;
  44913. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44914. return quatValue.add(offsetValue.scale(repeatCount));
  44915. }
  44916. return quatValue;
  44917. // Vector3
  44918. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44919. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  44920. switch (loopMode) {
  44921. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44922. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44923. return vec3Value;
  44924. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44925. return vec3Value.add(offsetValue.scale(repeatCount));
  44926. }
  44927. // Vector2
  44928. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44929. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  44930. switch (loopMode) {
  44931. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44932. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44933. return vec2Value;
  44934. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44935. return vec2Value.add(offsetValue.scale(repeatCount));
  44936. }
  44937. // Size
  44938. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44939. switch (loopMode) {
  44940. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44941. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44942. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  44943. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44944. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44945. }
  44946. // Color3
  44947. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44948. switch (loopMode) {
  44949. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44950. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44951. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  44952. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44953. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44954. }
  44955. // Matrix
  44956. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  44957. switch (loopMode) {
  44958. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44959. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44960. if (BABYLON.Animation.AllowMatricesInterpolation) {
  44961. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  44962. }
  44963. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44964. return startValue;
  44965. }
  44966. default:
  44967. break;
  44968. }
  44969. break;
  44970. }
  44971. }
  44972. return this._getKeyValue(keys[keys.length - 1].value);
  44973. };
  44974. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  44975. if (blend === void 0) { blend = false; }
  44976. // Set value
  44977. var path;
  44978. var destination;
  44979. var targetPropertyPath = this._animation.targetPropertyPath;
  44980. if (targetPropertyPath.length > 1) {
  44981. var property = this._target[targetPropertyPath[0]];
  44982. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  44983. property = property[targetPropertyPath[index]];
  44984. }
  44985. path = targetPropertyPath[targetPropertyPath.length - 1];
  44986. destination = property;
  44987. }
  44988. else {
  44989. path = targetPropertyPath[0];
  44990. destination = this._target;
  44991. }
  44992. // Blending
  44993. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  44994. if (!this._originalBlendValue) {
  44995. if (destination[path].clone) {
  44996. this._originalBlendValue = destination[path].clone();
  44997. }
  44998. else {
  44999. this._originalBlendValue = destination[path];
  45000. }
  45001. }
  45002. if (this._originalBlendValue.prototype) {
  45003. if (this._originalBlendValue.prototype.Lerp) {
  45004. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  45005. }
  45006. else {
  45007. destination[path] = currentValue;
  45008. }
  45009. }
  45010. else if (this._originalBlendValue.m) {
  45011. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  45012. }
  45013. else {
  45014. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  45015. }
  45016. this._blendingFactor += this._animation.blendingSpeed;
  45017. }
  45018. else {
  45019. destination[path] = currentValue;
  45020. }
  45021. if (this._target.markAsDirty) {
  45022. this._target.markAsDirty(this._animation.targetProperty);
  45023. }
  45024. };
  45025. RuntimeAnimation.prototype.goToFrame = function (frame) {
  45026. var keys = this._animation.getKeys();
  45027. if (frame < keys[0].frame) {
  45028. frame = keys[0].frame;
  45029. }
  45030. else if (frame > keys[keys.length - 1].frame) {
  45031. frame = keys[keys.length - 1].frame;
  45032. }
  45033. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  45034. this.setValue(currentValue);
  45035. };
  45036. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  45037. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  45038. this._ratioOffset = this._previousRatio - newRatio;
  45039. };
  45040. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  45041. if (blend === void 0) { blend = false; }
  45042. var targetPropertyPath = this._animation.targetPropertyPath;
  45043. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  45044. this._stopped = true;
  45045. return false;
  45046. }
  45047. var returnValue = true;
  45048. var keys = this._animation.getKeys();
  45049. // Adding a start key at frame 0 if missing
  45050. if (keys[0].frame !== 0) {
  45051. var newKey = { frame: 0, value: keys[0].value };
  45052. keys.splice(0, 0, newKey);
  45053. }
  45054. // Check limits
  45055. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  45056. from = keys[0].frame;
  45057. }
  45058. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  45059. to = keys[keys.length - 1].frame;
  45060. }
  45061. //to and from cannot be the same key
  45062. if (from === to) {
  45063. if (from > keys[0].frame) {
  45064. from--;
  45065. }
  45066. else if (to < keys[keys.length - 1].frame) {
  45067. to++;
  45068. }
  45069. }
  45070. // Compute ratio
  45071. var range = to - from;
  45072. var offsetValue;
  45073. // ratio represents the frame delta between from and to
  45074. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  45075. var highLimitValue = 0;
  45076. this._previousDelay = delay;
  45077. this._previousRatio = ratio;
  45078. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  45079. returnValue = false;
  45080. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  45081. }
  45082. else {
  45083. // Get max value if required
  45084. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  45085. var keyOffset = to.toString() + from.toString();
  45086. if (!this._offsetsCache[keyOffset]) {
  45087. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  45088. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  45089. switch (this._animation.dataType) {
  45090. // Float
  45091. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  45092. this._offsetsCache[keyOffset] = toValue - fromValue;
  45093. break;
  45094. // Quaternion
  45095. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  45096. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45097. break;
  45098. // Vector3
  45099. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  45100. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45101. // Vector2
  45102. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  45103. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45104. // Size
  45105. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  45106. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45107. // Color3
  45108. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  45109. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  45110. default:
  45111. break;
  45112. }
  45113. this._highLimitsCache[keyOffset] = toValue;
  45114. }
  45115. highLimitValue = this._highLimitsCache[keyOffset];
  45116. offsetValue = this._offsetsCache[keyOffset];
  45117. }
  45118. }
  45119. if (offsetValue === undefined) {
  45120. switch (this._animation.dataType) {
  45121. // Float
  45122. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  45123. offsetValue = 0;
  45124. break;
  45125. // Quaternion
  45126. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  45127. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  45128. break;
  45129. // Vector3
  45130. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  45131. offsetValue = BABYLON.Vector3.Zero();
  45132. break;
  45133. // Vector2
  45134. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  45135. offsetValue = BABYLON.Vector2.Zero();
  45136. break;
  45137. // Size
  45138. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  45139. offsetValue = BABYLON.Size.Zero();
  45140. break;
  45141. // Color3
  45142. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  45143. offsetValue = BABYLON.Color3.Black();
  45144. }
  45145. }
  45146. // Compute value
  45147. var repeatCount = (ratio / range) >> 0;
  45148. var currentFrame = returnValue ? from + ratio % range : to;
  45149. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  45150. // Set value
  45151. this.setValue(currentValue);
  45152. // Check events
  45153. var events = this._animation.getEvents();
  45154. for (var index = 0; index < events.length; index++) {
  45155. // Make sure current frame has passed event frame and that event frame is within the current range
  45156. // Also, handle both forward and reverse animations
  45157. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  45158. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  45159. var event = events[index];
  45160. if (!event.isDone) {
  45161. // If event should be done only once, remove it.
  45162. if (event.onlyOnce) {
  45163. events.splice(index, 1);
  45164. index--;
  45165. }
  45166. event.isDone = true;
  45167. event.action();
  45168. } // Don't do anything if the event has already be done.
  45169. }
  45170. else if (events[index].isDone && !events[index].onlyOnce) {
  45171. // reset event, the animation is looping
  45172. events[index].isDone = false;
  45173. }
  45174. }
  45175. if (!returnValue) {
  45176. this._stopped = true;
  45177. }
  45178. return returnValue;
  45179. };
  45180. return RuntimeAnimation;
  45181. }());
  45182. BABYLON.RuntimeAnimation = RuntimeAnimation;
  45183. })(BABYLON || (BABYLON = {}));
  45184. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  45185. var BABYLON;
  45186. (function (BABYLON) {
  45187. var Animatable = /** @class */ (function () {
  45188. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  45189. if (fromFrame === void 0) { fromFrame = 0; }
  45190. if (toFrame === void 0) { toFrame = 100; }
  45191. if (loopAnimation === void 0) { loopAnimation = false; }
  45192. if (speedRatio === void 0) { speedRatio = 1.0; }
  45193. this.target = target;
  45194. this.fromFrame = fromFrame;
  45195. this.toFrame = toFrame;
  45196. this.loopAnimation = loopAnimation;
  45197. this.onAnimationEnd = onAnimationEnd;
  45198. this._localDelayOffset = null;
  45199. this._pausedDelay = null;
  45200. this._runtimeAnimations = new Array();
  45201. this._paused = false;
  45202. this._speedRatio = 1;
  45203. this.animationStarted = false;
  45204. if (animations) {
  45205. this.appendAnimations(target, animations);
  45206. }
  45207. this._speedRatio = speedRatio;
  45208. this._scene = scene;
  45209. scene._activeAnimatables.push(this);
  45210. }
  45211. Object.defineProperty(Animatable.prototype, "speedRatio", {
  45212. get: function () {
  45213. return this._speedRatio;
  45214. },
  45215. set: function (value) {
  45216. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  45217. var animation = this._runtimeAnimations[index];
  45218. animation._prepareForSpeedRatioChange(value);
  45219. }
  45220. this._speedRatio = value;
  45221. },
  45222. enumerable: true,
  45223. configurable: true
  45224. });
  45225. // Methods
  45226. Animatable.prototype.getAnimations = function () {
  45227. return this._runtimeAnimations;
  45228. };
  45229. Animatable.prototype.appendAnimations = function (target, animations) {
  45230. for (var index = 0; index < animations.length; index++) {
  45231. var animation = animations[index];
  45232. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  45233. }
  45234. };
  45235. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  45236. var runtimeAnimations = this._runtimeAnimations;
  45237. for (var index = 0; index < runtimeAnimations.length; index++) {
  45238. if (runtimeAnimations[index].animation.targetProperty === property) {
  45239. return runtimeAnimations[index].animation;
  45240. }
  45241. }
  45242. return null;
  45243. };
  45244. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  45245. var runtimeAnimations = this._runtimeAnimations;
  45246. for (var index = 0; index < runtimeAnimations.length; index++) {
  45247. if (runtimeAnimations[index].animation.targetProperty === property) {
  45248. return runtimeAnimations[index];
  45249. }
  45250. }
  45251. return null;
  45252. };
  45253. Animatable.prototype.reset = function () {
  45254. var runtimeAnimations = this._runtimeAnimations;
  45255. for (var index = 0; index < runtimeAnimations.length; index++) {
  45256. runtimeAnimations[index].reset();
  45257. }
  45258. // Reset to original value
  45259. for (index = 0; index < runtimeAnimations.length; index++) {
  45260. var animation = runtimeAnimations[index];
  45261. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  45262. }
  45263. this._localDelayOffset = null;
  45264. this._pausedDelay = null;
  45265. };
  45266. Animatable.prototype.enableBlending = function (blendingSpeed) {
  45267. var runtimeAnimations = this._runtimeAnimations;
  45268. for (var index = 0; index < runtimeAnimations.length; index++) {
  45269. runtimeAnimations[index].animation.enableBlending = true;
  45270. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  45271. }
  45272. };
  45273. Animatable.prototype.disableBlending = function () {
  45274. var runtimeAnimations = this._runtimeAnimations;
  45275. for (var index = 0; index < runtimeAnimations.length; index++) {
  45276. runtimeAnimations[index].animation.enableBlending = false;
  45277. }
  45278. };
  45279. Animatable.prototype.goToFrame = function (frame) {
  45280. var runtimeAnimations = this._runtimeAnimations;
  45281. if (runtimeAnimations[0]) {
  45282. var fps = runtimeAnimations[0].animation.framePerSecond;
  45283. var currentFrame = runtimeAnimations[0].currentFrame;
  45284. var adjustTime = frame - currentFrame;
  45285. var delay = adjustTime * 1000 / fps;
  45286. if (this._localDelayOffset === null) {
  45287. this._localDelayOffset = 0;
  45288. }
  45289. this._localDelayOffset -= delay;
  45290. }
  45291. for (var index = 0; index < runtimeAnimations.length; index++) {
  45292. runtimeAnimations[index].goToFrame(frame);
  45293. }
  45294. };
  45295. Animatable.prototype.pause = function () {
  45296. if (this._paused) {
  45297. return;
  45298. }
  45299. this._paused = true;
  45300. };
  45301. Animatable.prototype.restart = function () {
  45302. this._paused = false;
  45303. };
  45304. Animatable.prototype.stop = function (animationName) {
  45305. if (animationName) {
  45306. var idx = this._scene._activeAnimatables.indexOf(this);
  45307. if (idx > -1) {
  45308. var runtimeAnimations = this._runtimeAnimations;
  45309. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  45310. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  45311. continue;
  45312. }
  45313. runtimeAnimations[index].dispose();
  45314. runtimeAnimations.splice(index, 1);
  45315. }
  45316. if (runtimeAnimations.length == 0) {
  45317. this._scene._activeAnimatables.splice(idx, 1);
  45318. if (this.onAnimationEnd) {
  45319. this.onAnimationEnd();
  45320. }
  45321. }
  45322. }
  45323. }
  45324. else {
  45325. var index = this._scene._activeAnimatables.indexOf(this);
  45326. if (index > -1) {
  45327. this._scene._activeAnimatables.splice(index, 1);
  45328. var runtimeAnimations = this._runtimeAnimations;
  45329. for (var index = 0; index < runtimeAnimations.length; index++) {
  45330. runtimeAnimations[index].dispose();
  45331. }
  45332. if (this.onAnimationEnd) {
  45333. this.onAnimationEnd();
  45334. }
  45335. }
  45336. }
  45337. };
  45338. Animatable.prototype._animate = function (delay) {
  45339. if (this._paused) {
  45340. this.animationStarted = false;
  45341. if (this._pausedDelay === null) {
  45342. this._pausedDelay = delay;
  45343. }
  45344. return true;
  45345. }
  45346. if (this._localDelayOffset === null) {
  45347. this._localDelayOffset = delay;
  45348. this._pausedDelay = null;
  45349. }
  45350. else if (this._pausedDelay !== null) {
  45351. this._localDelayOffset += delay - this._pausedDelay;
  45352. this._pausedDelay = null;
  45353. }
  45354. // Animating
  45355. var running = false;
  45356. var runtimeAnimations = this._runtimeAnimations;
  45357. var index;
  45358. for (index = 0; index < runtimeAnimations.length; index++) {
  45359. var animation = runtimeAnimations[index];
  45360. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  45361. running = running || isRunning;
  45362. }
  45363. this.animationStarted = running;
  45364. if (!running) {
  45365. // Remove from active animatables
  45366. index = this._scene._activeAnimatables.indexOf(this);
  45367. this._scene._activeAnimatables.splice(index, 1);
  45368. // Dispose all runtime animations
  45369. for (index = 0; index < runtimeAnimations.length; index++) {
  45370. runtimeAnimations[index].dispose();
  45371. }
  45372. }
  45373. if (!running && this.onAnimationEnd) {
  45374. this.onAnimationEnd();
  45375. this.onAnimationEnd = null;
  45376. }
  45377. return running;
  45378. };
  45379. return Animatable;
  45380. }());
  45381. BABYLON.Animatable = Animatable;
  45382. })(BABYLON || (BABYLON = {}));
  45383. //# sourceMappingURL=babylon.animatable.js.map
  45384. var BABYLON;
  45385. (function (BABYLON) {
  45386. var EasingFunction = /** @class */ (function () {
  45387. function EasingFunction() {
  45388. // Properties
  45389. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  45390. }
  45391. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  45392. get: function () {
  45393. return EasingFunction._EASINGMODE_EASEIN;
  45394. },
  45395. enumerable: true,
  45396. configurable: true
  45397. });
  45398. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  45399. get: function () {
  45400. return EasingFunction._EASINGMODE_EASEOUT;
  45401. },
  45402. enumerable: true,
  45403. configurable: true
  45404. });
  45405. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  45406. get: function () {
  45407. return EasingFunction._EASINGMODE_EASEINOUT;
  45408. },
  45409. enumerable: true,
  45410. configurable: true
  45411. });
  45412. EasingFunction.prototype.setEasingMode = function (easingMode) {
  45413. var n = Math.min(Math.max(easingMode, 0), 2);
  45414. this._easingMode = n;
  45415. };
  45416. EasingFunction.prototype.getEasingMode = function () {
  45417. return this._easingMode;
  45418. };
  45419. EasingFunction.prototype.easeInCore = function (gradient) {
  45420. throw new Error('You must implement this method');
  45421. };
  45422. EasingFunction.prototype.ease = function (gradient) {
  45423. switch (this._easingMode) {
  45424. case EasingFunction.EASINGMODE_EASEIN:
  45425. return this.easeInCore(gradient);
  45426. case EasingFunction.EASINGMODE_EASEOUT:
  45427. return (1 - this.easeInCore(1 - gradient));
  45428. }
  45429. if (gradient >= 0.5) {
  45430. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  45431. }
  45432. return (this.easeInCore(gradient * 2) * 0.5);
  45433. };
  45434. //Statics
  45435. EasingFunction._EASINGMODE_EASEIN = 0;
  45436. EasingFunction._EASINGMODE_EASEOUT = 1;
  45437. EasingFunction._EASINGMODE_EASEINOUT = 2;
  45438. return EasingFunction;
  45439. }());
  45440. BABYLON.EasingFunction = EasingFunction;
  45441. var CircleEase = /** @class */ (function (_super) {
  45442. __extends(CircleEase, _super);
  45443. function CircleEase() {
  45444. return _super !== null && _super.apply(this, arguments) || this;
  45445. }
  45446. CircleEase.prototype.easeInCore = function (gradient) {
  45447. gradient = Math.max(0, Math.min(1, gradient));
  45448. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  45449. };
  45450. return CircleEase;
  45451. }(EasingFunction));
  45452. BABYLON.CircleEase = CircleEase;
  45453. var BackEase = /** @class */ (function (_super) {
  45454. __extends(BackEase, _super);
  45455. function BackEase(amplitude) {
  45456. if (amplitude === void 0) { amplitude = 1; }
  45457. var _this = _super.call(this) || this;
  45458. _this.amplitude = amplitude;
  45459. return _this;
  45460. }
  45461. BackEase.prototype.easeInCore = function (gradient) {
  45462. var num = Math.max(0, this.amplitude);
  45463. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  45464. };
  45465. return BackEase;
  45466. }(EasingFunction));
  45467. BABYLON.BackEase = BackEase;
  45468. var BounceEase = /** @class */ (function (_super) {
  45469. __extends(BounceEase, _super);
  45470. function BounceEase(bounces, bounciness) {
  45471. if (bounces === void 0) { bounces = 3; }
  45472. if (bounciness === void 0) { bounciness = 2; }
  45473. var _this = _super.call(this) || this;
  45474. _this.bounces = bounces;
  45475. _this.bounciness = bounciness;
  45476. return _this;
  45477. }
  45478. BounceEase.prototype.easeInCore = function (gradient) {
  45479. var y = Math.max(0.0, this.bounces);
  45480. var bounciness = this.bounciness;
  45481. if (bounciness <= 1.0) {
  45482. bounciness = 1.001;
  45483. }
  45484. var num9 = Math.pow(bounciness, y);
  45485. var num5 = 1.0 - bounciness;
  45486. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  45487. var num15 = gradient * num4;
  45488. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  45489. var num3 = Math.floor(num65);
  45490. var num13 = num3 + 1.0;
  45491. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  45492. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  45493. var num7 = (num8 + num12) * 0.5;
  45494. var num6 = gradient - num7;
  45495. var num2 = num7 - num8;
  45496. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  45497. };
  45498. return BounceEase;
  45499. }(EasingFunction));
  45500. BABYLON.BounceEase = BounceEase;
  45501. var CubicEase = /** @class */ (function (_super) {
  45502. __extends(CubicEase, _super);
  45503. function CubicEase() {
  45504. return _super !== null && _super.apply(this, arguments) || this;
  45505. }
  45506. CubicEase.prototype.easeInCore = function (gradient) {
  45507. return (gradient * gradient * gradient);
  45508. };
  45509. return CubicEase;
  45510. }(EasingFunction));
  45511. BABYLON.CubicEase = CubicEase;
  45512. var ElasticEase = /** @class */ (function (_super) {
  45513. __extends(ElasticEase, _super);
  45514. function ElasticEase(oscillations, springiness) {
  45515. if (oscillations === void 0) { oscillations = 3; }
  45516. if (springiness === void 0) { springiness = 3; }
  45517. var _this = _super.call(this) || this;
  45518. _this.oscillations = oscillations;
  45519. _this.springiness = springiness;
  45520. return _this;
  45521. }
  45522. ElasticEase.prototype.easeInCore = function (gradient) {
  45523. var num2;
  45524. var num3 = Math.max(0.0, this.oscillations);
  45525. var num = Math.max(0.0, this.springiness);
  45526. if (num == 0) {
  45527. num2 = gradient;
  45528. }
  45529. else {
  45530. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  45531. }
  45532. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  45533. };
  45534. return ElasticEase;
  45535. }(EasingFunction));
  45536. BABYLON.ElasticEase = ElasticEase;
  45537. var ExponentialEase = /** @class */ (function (_super) {
  45538. __extends(ExponentialEase, _super);
  45539. function ExponentialEase(exponent) {
  45540. if (exponent === void 0) { exponent = 2; }
  45541. var _this = _super.call(this) || this;
  45542. _this.exponent = exponent;
  45543. return _this;
  45544. }
  45545. ExponentialEase.prototype.easeInCore = function (gradient) {
  45546. if (this.exponent <= 0) {
  45547. return gradient;
  45548. }
  45549. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  45550. };
  45551. return ExponentialEase;
  45552. }(EasingFunction));
  45553. BABYLON.ExponentialEase = ExponentialEase;
  45554. var PowerEase = /** @class */ (function (_super) {
  45555. __extends(PowerEase, _super);
  45556. function PowerEase(power) {
  45557. if (power === void 0) { power = 2; }
  45558. var _this = _super.call(this) || this;
  45559. _this.power = power;
  45560. return _this;
  45561. }
  45562. PowerEase.prototype.easeInCore = function (gradient) {
  45563. var y = Math.max(0.0, this.power);
  45564. return Math.pow(gradient, y);
  45565. };
  45566. return PowerEase;
  45567. }(EasingFunction));
  45568. BABYLON.PowerEase = PowerEase;
  45569. var QuadraticEase = /** @class */ (function (_super) {
  45570. __extends(QuadraticEase, _super);
  45571. function QuadraticEase() {
  45572. return _super !== null && _super.apply(this, arguments) || this;
  45573. }
  45574. QuadraticEase.prototype.easeInCore = function (gradient) {
  45575. return (gradient * gradient);
  45576. };
  45577. return QuadraticEase;
  45578. }(EasingFunction));
  45579. BABYLON.QuadraticEase = QuadraticEase;
  45580. var QuarticEase = /** @class */ (function (_super) {
  45581. __extends(QuarticEase, _super);
  45582. function QuarticEase() {
  45583. return _super !== null && _super.apply(this, arguments) || this;
  45584. }
  45585. QuarticEase.prototype.easeInCore = function (gradient) {
  45586. return (gradient * gradient * gradient * gradient);
  45587. };
  45588. return QuarticEase;
  45589. }(EasingFunction));
  45590. BABYLON.QuarticEase = QuarticEase;
  45591. var QuinticEase = /** @class */ (function (_super) {
  45592. __extends(QuinticEase, _super);
  45593. function QuinticEase() {
  45594. return _super !== null && _super.apply(this, arguments) || this;
  45595. }
  45596. QuinticEase.prototype.easeInCore = function (gradient) {
  45597. return (gradient * gradient * gradient * gradient * gradient);
  45598. };
  45599. return QuinticEase;
  45600. }(EasingFunction));
  45601. BABYLON.QuinticEase = QuinticEase;
  45602. var SineEase = /** @class */ (function (_super) {
  45603. __extends(SineEase, _super);
  45604. function SineEase() {
  45605. return _super !== null && _super.apply(this, arguments) || this;
  45606. }
  45607. SineEase.prototype.easeInCore = function (gradient) {
  45608. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  45609. };
  45610. return SineEase;
  45611. }(EasingFunction));
  45612. BABYLON.SineEase = SineEase;
  45613. var BezierCurveEase = /** @class */ (function (_super) {
  45614. __extends(BezierCurveEase, _super);
  45615. function BezierCurveEase(x1, y1, x2, y2) {
  45616. if (x1 === void 0) { x1 = 0; }
  45617. if (y1 === void 0) { y1 = 0; }
  45618. if (x2 === void 0) { x2 = 1; }
  45619. if (y2 === void 0) { y2 = 1; }
  45620. var _this = _super.call(this) || this;
  45621. _this.x1 = x1;
  45622. _this.y1 = y1;
  45623. _this.x2 = x2;
  45624. _this.y2 = y2;
  45625. return _this;
  45626. }
  45627. BezierCurveEase.prototype.easeInCore = function (gradient) {
  45628. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  45629. };
  45630. return BezierCurveEase;
  45631. }(EasingFunction));
  45632. BABYLON.BezierCurveEase = BezierCurveEase;
  45633. })(BABYLON || (BABYLON = {}));
  45634. //# sourceMappingURL=babylon.easing.js.map
  45635. var BABYLON;
  45636. (function (BABYLON) {
  45637. var Condition = /** @class */ (function () {
  45638. function Condition(actionManager) {
  45639. this._actionManager = actionManager;
  45640. }
  45641. Condition.prototype.isValid = function () {
  45642. return true;
  45643. };
  45644. Condition.prototype._getProperty = function (propertyPath) {
  45645. return this._actionManager._getProperty(propertyPath);
  45646. };
  45647. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  45648. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45649. };
  45650. Condition.prototype.serialize = function () {
  45651. };
  45652. Condition.prototype._serialize = function (serializedCondition) {
  45653. return {
  45654. type: 2,
  45655. children: [],
  45656. name: serializedCondition.name,
  45657. properties: serializedCondition.properties
  45658. };
  45659. };
  45660. return Condition;
  45661. }());
  45662. BABYLON.Condition = Condition;
  45663. var ValueCondition = /** @class */ (function (_super) {
  45664. __extends(ValueCondition, _super);
  45665. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  45666. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  45667. var _this = _super.call(this, actionManager) || this;
  45668. _this.propertyPath = propertyPath;
  45669. _this.value = value;
  45670. _this.operator = operator;
  45671. _this._target = target;
  45672. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  45673. _this._property = _this._getProperty(_this.propertyPath);
  45674. return _this;
  45675. }
  45676. Object.defineProperty(ValueCondition, "IsEqual", {
  45677. get: function () {
  45678. return ValueCondition._IsEqual;
  45679. },
  45680. enumerable: true,
  45681. configurable: true
  45682. });
  45683. Object.defineProperty(ValueCondition, "IsDifferent", {
  45684. get: function () {
  45685. return ValueCondition._IsDifferent;
  45686. },
  45687. enumerable: true,
  45688. configurable: true
  45689. });
  45690. Object.defineProperty(ValueCondition, "IsGreater", {
  45691. get: function () {
  45692. return ValueCondition._IsGreater;
  45693. },
  45694. enumerable: true,
  45695. configurable: true
  45696. });
  45697. Object.defineProperty(ValueCondition, "IsLesser", {
  45698. get: function () {
  45699. return ValueCondition._IsLesser;
  45700. },
  45701. enumerable: true,
  45702. configurable: true
  45703. });
  45704. // Methods
  45705. ValueCondition.prototype.isValid = function () {
  45706. switch (this.operator) {
  45707. case ValueCondition.IsGreater:
  45708. return this._effectiveTarget[this._property] > this.value;
  45709. case ValueCondition.IsLesser:
  45710. return this._effectiveTarget[this._property] < this.value;
  45711. case ValueCondition.IsEqual:
  45712. case ValueCondition.IsDifferent:
  45713. var check;
  45714. if (this.value.equals) {
  45715. check = this.value.equals(this._effectiveTarget[this._property]);
  45716. }
  45717. else {
  45718. check = this.value === this._effectiveTarget[this._property];
  45719. }
  45720. return this.operator === ValueCondition.IsEqual ? check : !check;
  45721. }
  45722. return false;
  45723. };
  45724. ValueCondition.prototype.serialize = function () {
  45725. return this._serialize({
  45726. name: "ValueCondition",
  45727. properties: [
  45728. BABYLON.Action._GetTargetProperty(this._target),
  45729. { name: "propertyPath", value: this.propertyPath },
  45730. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45731. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  45732. ]
  45733. });
  45734. };
  45735. ValueCondition.GetOperatorName = function (operator) {
  45736. switch (operator) {
  45737. case ValueCondition._IsEqual: return "IsEqual";
  45738. case ValueCondition._IsDifferent: return "IsDifferent";
  45739. case ValueCondition._IsGreater: return "IsGreater";
  45740. case ValueCondition._IsLesser: return "IsLesser";
  45741. default: return "";
  45742. }
  45743. };
  45744. // Statics
  45745. ValueCondition._IsEqual = 0;
  45746. ValueCondition._IsDifferent = 1;
  45747. ValueCondition._IsGreater = 2;
  45748. ValueCondition._IsLesser = 3;
  45749. return ValueCondition;
  45750. }(Condition));
  45751. BABYLON.ValueCondition = ValueCondition;
  45752. var PredicateCondition = /** @class */ (function (_super) {
  45753. __extends(PredicateCondition, _super);
  45754. function PredicateCondition(actionManager, predicate) {
  45755. var _this = _super.call(this, actionManager) || this;
  45756. _this.predicate = predicate;
  45757. return _this;
  45758. }
  45759. PredicateCondition.prototype.isValid = function () {
  45760. return this.predicate();
  45761. };
  45762. return PredicateCondition;
  45763. }(Condition));
  45764. BABYLON.PredicateCondition = PredicateCondition;
  45765. var StateCondition = /** @class */ (function (_super) {
  45766. __extends(StateCondition, _super);
  45767. function StateCondition(actionManager, target, value) {
  45768. var _this = _super.call(this, actionManager) || this;
  45769. _this.value = value;
  45770. _this._target = target;
  45771. return _this;
  45772. }
  45773. // Methods
  45774. StateCondition.prototype.isValid = function () {
  45775. return this._target.state === this.value;
  45776. };
  45777. StateCondition.prototype.serialize = function () {
  45778. return this._serialize({
  45779. name: "StateCondition",
  45780. properties: [
  45781. BABYLON.Action._GetTargetProperty(this._target),
  45782. { name: "value", value: this.value }
  45783. ]
  45784. });
  45785. };
  45786. return StateCondition;
  45787. }(Condition));
  45788. BABYLON.StateCondition = StateCondition;
  45789. })(BABYLON || (BABYLON = {}));
  45790. //# sourceMappingURL=babylon.condition.js.map
  45791. var BABYLON;
  45792. (function (BABYLON) {
  45793. var Action = /** @class */ (function () {
  45794. function Action(triggerOptions, condition) {
  45795. this.triggerOptions = triggerOptions;
  45796. this.onBeforeExecuteObservable = new BABYLON.Observable();
  45797. if (triggerOptions.parameter) {
  45798. this.trigger = triggerOptions.trigger;
  45799. this._triggerParameter = triggerOptions.parameter;
  45800. }
  45801. else {
  45802. this.trigger = triggerOptions;
  45803. }
  45804. this._nextActiveAction = this;
  45805. this._condition = condition;
  45806. }
  45807. // Methods
  45808. Action.prototype._prepare = function () {
  45809. };
  45810. Action.prototype.getTriggerParameter = function () {
  45811. return this._triggerParameter;
  45812. };
  45813. Action.prototype._executeCurrent = function (evt) {
  45814. if (this._nextActiveAction._condition) {
  45815. var condition = this._nextActiveAction._condition;
  45816. var currentRenderId = this._actionManager.getScene().getRenderId();
  45817. // We cache the current evaluation for the current frame
  45818. if (condition._evaluationId === currentRenderId) {
  45819. if (!condition._currentResult) {
  45820. return;
  45821. }
  45822. }
  45823. else {
  45824. condition._evaluationId = currentRenderId;
  45825. if (!condition.isValid()) {
  45826. condition._currentResult = false;
  45827. return;
  45828. }
  45829. condition._currentResult = true;
  45830. }
  45831. }
  45832. this.onBeforeExecuteObservable.notifyObservers(this);
  45833. this._nextActiveAction.execute(evt);
  45834. this.skipToNextActiveAction();
  45835. };
  45836. Action.prototype.execute = function (evt) {
  45837. };
  45838. Action.prototype.skipToNextActiveAction = function () {
  45839. if (this._nextActiveAction._child) {
  45840. if (!this._nextActiveAction._child._actionManager) {
  45841. this._nextActiveAction._child._actionManager = this._actionManager;
  45842. }
  45843. this._nextActiveAction = this._nextActiveAction._child;
  45844. }
  45845. else {
  45846. this._nextActiveAction = this;
  45847. }
  45848. };
  45849. Action.prototype.then = function (action) {
  45850. this._child = action;
  45851. action._actionManager = this._actionManager;
  45852. action._prepare();
  45853. return action;
  45854. };
  45855. Action.prototype._getProperty = function (propertyPath) {
  45856. return this._actionManager._getProperty(propertyPath);
  45857. };
  45858. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  45859. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45860. };
  45861. Action.prototype.serialize = function (parent) {
  45862. };
  45863. // Called by BABYLON.Action objects in serialize(...). Internal use
  45864. Action.prototype._serialize = function (serializedAction, parent) {
  45865. var serializationObject = {
  45866. type: 1,
  45867. children: [],
  45868. name: serializedAction.name,
  45869. properties: serializedAction.properties || []
  45870. };
  45871. // Serialize child
  45872. if (this._child) {
  45873. this._child.serialize(serializationObject);
  45874. }
  45875. // Check if "this" has a condition
  45876. if (this._condition) {
  45877. var serializedCondition = this._condition.serialize();
  45878. serializedCondition.children.push(serializationObject);
  45879. if (parent) {
  45880. parent.children.push(serializedCondition);
  45881. }
  45882. return serializedCondition;
  45883. }
  45884. if (parent) {
  45885. parent.children.push(serializationObject);
  45886. }
  45887. return serializationObject;
  45888. };
  45889. Action._SerializeValueAsString = function (value) {
  45890. if (typeof value === "number") {
  45891. return value.toString();
  45892. }
  45893. if (typeof value === "boolean") {
  45894. return value ? "true" : "false";
  45895. }
  45896. if (value instanceof BABYLON.Vector2) {
  45897. return value.x + ", " + value.y;
  45898. }
  45899. if (value instanceof BABYLON.Vector3) {
  45900. return value.x + ", " + value.y + ", " + value.z;
  45901. }
  45902. if (value instanceof BABYLON.Color3) {
  45903. return value.r + ", " + value.g + ", " + value.b;
  45904. }
  45905. if (value instanceof BABYLON.Color4) {
  45906. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  45907. }
  45908. return value; // string
  45909. };
  45910. Action._GetTargetProperty = function (target) {
  45911. return {
  45912. name: "target",
  45913. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  45914. : target instanceof BABYLON.Light ? "LightProperties"
  45915. : target instanceof BABYLON.Camera ? "CameraProperties"
  45916. : "SceneProperties",
  45917. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  45918. };
  45919. };
  45920. return Action;
  45921. }());
  45922. BABYLON.Action = Action;
  45923. })(BABYLON || (BABYLON = {}));
  45924. //# sourceMappingURL=babylon.action.js.map
  45925. var BABYLON;
  45926. (function (BABYLON) {
  45927. /**
  45928. * ActionEvent is the event beint sent when an action is triggered.
  45929. */
  45930. var ActionEvent = /** @class */ (function () {
  45931. /**
  45932. * @param source The mesh or sprite that triggered the action.
  45933. * @param pointerX The X mouse cursor position at the time of the event
  45934. * @param pointerY The Y mouse cursor position at the time of the event
  45935. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  45936. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  45937. */
  45938. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  45939. this.source = source;
  45940. this.pointerX = pointerX;
  45941. this.pointerY = pointerY;
  45942. this.meshUnderPointer = meshUnderPointer;
  45943. this.sourceEvent = sourceEvent;
  45944. this.additionalData = additionalData;
  45945. }
  45946. /**
  45947. * Helper function to auto-create an ActionEvent from a source mesh.
  45948. * @param source The source mesh that triggered the event
  45949. * @param evt {Event} The original (browser) event
  45950. */
  45951. ActionEvent.CreateNew = function (source, evt, additionalData) {
  45952. var scene = source.getScene();
  45953. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45954. };
  45955. /**
  45956. * Helper function to auto-create an ActionEvent from a source mesh.
  45957. * @param source The source sprite that triggered the event
  45958. * @param scene Scene associated with the sprite
  45959. * @param evt {Event} The original (browser) event
  45960. */
  45961. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  45962. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45963. };
  45964. /**
  45965. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  45966. * @param scene the scene where the event occurred
  45967. * @param evt {Event} The original (browser) event
  45968. */
  45969. ActionEvent.CreateNewFromScene = function (scene, evt) {
  45970. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  45971. };
  45972. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  45973. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  45974. };
  45975. return ActionEvent;
  45976. }());
  45977. BABYLON.ActionEvent = ActionEvent;
  45978. /**
  45979. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  45980. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  45981. */
  45982. var ActionManager = /** @class */ (function () {
  45983. function ActionManager(scene) {
  45984. // Members
  45985. this.actions = new Array();
  45986. this.hoverCursor = '';
  45987. this._scene = scene;
  45988. scene._actionManagers.push(this);
  45989. }
  45990. Object.defineProperty(ActionManager, "NothingTrigger", {
  45991. get: function () {
  45992. return ActionManager._NothingTrigger;
  45993. },
  45994. enumerable: true,
  45995. configurable: true
  45996. });
  45997. Object.defineProperty(ActionManager, "OnPickTrigger", {
  45998. get: function () {
  45999. return ActionManager._OnPickTrigger;
  46000. },
  46001. enumerable: true,
  46002. configurable: true
  46003. });
  46004. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  46005. get: function () {
  46006. return ActionManager._OnLeftPickTrigger;
  46007. },
  46008. enumerable: true,
  46009. configurable: true
  46010. });
  46011. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  46012. get: function () {
  46013. return ActionManager._OnRightPickTrigger;
  46014. },
  46015. enumerable: true,
  46016. configurable: true
  46017. });
  46018. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  46019. get: function () {
  46020. return ActionManager._OnCenterPickTrigger;
  46021. },
  46022. enumerable: true,
  46023. configurable: true
  46024. });
  46025. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  46026. get: function () {
  46027. return ActionManager._OnPickDownTrigger;
  46028. },
  46029. enumerable: true,
  46030. configurable: true
  46031. });
  46032. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  46033. get: function () {
  46034. return ActionManager._OnDoublePickTrigger;
  46035. },
  46036. enumerable: true,
  46037. configurable: true
  46038. });
  46039. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  46040. get: function () {
  46041. return ActionManager._OnPickUpTrigger;
  46042. },
  46043. enumerable: true,
  46044. configurable: true
  46045. });
  46046. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  46047. /// This trigger will only be raised if you also declared a OnPickDown
  46048. get: function () {
  46049. return ActionManager._OnPickOutTrigger;
  46050. },
  46051. enumerable: true,
  46052. configurable: true
  46053. });
  46054. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  46055. get: function () {
  46056. return ActionManager._OnLongPressTrigger;
  46057. },
  46058. enumerable: true,
  46059. configurable: true
  46060. });
  46061. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  46062. get: function () {
  46063. return ActionManager._OnPointerOverTrigger;
  46064. },
  46065. enumerable: true,
  46066. configurable: true
  46067. });
  46068. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  46069. get: function () {
  46070. return ActionManager._OnPointerOutTrigger;
  46071. },
  46072. enumerable: true,
  46073. configurable: true
  46074. });
  46075. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  46076. get: function () {
  46077. return ActionManager._OnEveryFrameTrigger;
  46078. },
  46079. enumerable: true,
  46080. configurable: true
  46081. });
  46082. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  46083. get: function () {
  46084. return ActionManager._OnIntersectionEnterTrigger;
  46085. },
  46086. enumerable: true,
  46087. configurable: true
  46088. });
  46089. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  46090. get: function () {
  46091. return ActionManager._OnIntersectionExitTrigger;
  46092. },
  46093. enumerable: true,
  46094. configurable: true
  46095. });
  46096. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  46097. get: function () {
  46098. return ActionManager._OnKeyDownTrigger;
  46099. },
  46100. enumerable: true,
  46101. configurable: true
  46102. });
  46103. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  46104. get: function () {
  46105. return ActionManager._OnKeyUpTrigger;
  46106. },
  46107. enumerable: true,
  46108. configurable: true
  46109. });
  46110. // Methods
  46111. ActionManager.prototype.dispose = function () {
  46112. var index = this._scene._actionManagers.indexOf(this);
  46113. for (var i = 0; i < this.actions.length; i++) {
  46114. var action = this.actions[i];
  46115. ActionManager.Triggers[action.trigger]--;
  46116. if (ActionManager.Triggers[action.trigger] === 0) {
  46117. delete ActionManager.Triggers[action.trigger];
  46118. }
  46119. }
  46120. if (index > -1) {
  46121. this._scene._actionManagers.splice(index, 1);
  46122. }
  46123. };
  46124. ActionManager.prototype.getScene = function () {
  46125. return this._scene;
  46126. };
  46127. /**
  46128. * Does this action manager handles actions of any of the given triggers
  46129. * @param {number[]} triggers - the triggers to be tested
  46130. * @return {boolean} whether one (or more) of the triggers is handeled
  46131. */
  46132. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  46133. for (var index = 0; index < this.actions.length; index++) {
  46134. var action = this.actions[index];
  46135. if (triggers.indexOf(action.trigger) > -1) {
  46136. return true;
  46137. }
  46138. }
  46139. return false;
  46140. };
  46141. /**
  46142. * Does this action manager handles actions of a given trigger
  46143. * @param {number} trigger - the trigger to be tested
  46144. * @return {boolean} whether the trigger is handeled
  46145. */
  46146. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  46147. for (var index = 0; index < this.actions.length; index++) {
  46148. var action = this.actions[index];
  46149. if (action.trigger === trigger) {
  46150. return true;
  46151. }
  46152. }
  46153. return false;
  46154. };
  46155. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  46156. /**
  46157. * Does this action manager has pointer triggers
  46158. * @return {boolean} whether or not it has pointer triggers
  46159. */
  46160. get: function () {
  46161. for (var index = 0; index < this.actions.length; index++) {
  46162. var action = this.actions[index];
  46163. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  46164. return true;
  46165. }
  46166. }
  46167. return false;
  46168. },
  46169. enumerable: true,
  46170. configurable: true
  46171. });
  46172. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  46173. /**
  46174. * Does this action manager has pick triggers
  46175. * @return {boolean} whether or not it has pick triggers
  46176. */
  46177. get: function () {
  46178. for (var index = 0; index < this.actions.length; index++) {
  46179. var action = this.actions[index];
  46180. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  46181. return true;
  46182. }
  46183. }
  46184. return false;
  46185. },
  46186. enumerable: true,
  46187. configurable: true
  46188. });
  46189. Object.defineProperty(ActionManager, "HasTriggers", {
  46190. /**
  46191. * Does exist one action manager with at least one trigger
  46192. * @return {boolean} whether or not it exists one action manager with one trigger
  46193. **/
  46194. get: function () {
  46195. for (var t in ActionManager.Triggers) {
  46196. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46197. return true;
  46198. }
  46199. }
  46200. return false;
  46201. },
  46202. enumerable: true,
  46203. configurable: true
  46204. });
  46205. Object.defineProperty(ActionManager, "HasPickTriggers", {
  46206. /**
  46207. * Does exist one action manager with at least one pick trigger
  46208. * @return {boolean} whether or not it exists one action manager with one pick trigger
  46209. **/
  46210. get: function () {
  46211. for (var t in ActionManager.Triggers) {
  46212. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46213. var t_int = parseInt(t);
  46214. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  46215. return true;
  46216. }
  46217. }
  46218. }
  46219. return false;
  46220. },
  46221. enumerable: true,
  46222. configurable: true
  46223. });
  46224. /**
  46225. * Does exist one action manager that handles actions of a given trigger
  46226. * @param {number} trigger - the trigger to be tested
  46227. * @return {boolean} whether the trigger is handeled by at least one action manager
  46228. **/
  46229. ActionManager.HasSpecificTrigger = function (trigger) {
  46230. for (var t in ActionManager.Triggers) {
  46231. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46232. var t_int = parseInt(t);
  46233. if (t_int === trigger) {
  46234. return true;
  46235. }
  46236. }
  46237. }
  46238. return false;
  46239. };
  46240. /**
  46241. * Registers an action to this action manager
  46242. * @param {BABYLON.Action} action - the action to be registered
  46243. * @return {BABYLON.Action} the action amended (prepared) after registration
  46244. */
  46245. ActionManager.prototype.registerAction = function (action) {
  46246. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46247. if (this.getScene().actionManager !== this) {
  46248. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46249. return null;
  46250. }
  46251. }
  46252. this.actions.push(action);
  46253. if (ActionManager.Triggers[action.trigger]) {
  46254. ActionManager.Triggers[action.trigger]++;
  46255. }
  46256. else {
  46257. ActionManager.Triggers[action.trigger] = 1;
  46258. }
  46259. action._actionManager = this;
  46260. action._prepare();
  46261. return action;
  46262. };
  46263. /**
  46264. * Unregisters an action to this action manager
  46265. * @param action The action to be unregistered
  46266. * @return whether the action has been unregistered
  46267. */
  46268. ActionManager.prototype.unregisterAction = function (action) {
  46269. var index = this.actions.indexOf(action);
  46270. if (index !== -1) {
  46271. this.actions.splice(index, 1);
  46272. ActionManager.Triggers[action.trigger] -= 1;
  46273. if (ActionManager.Triggers[action.trigger] === 0) {
  46274. delete ActionManager.Triggers[action.trigger];
  46275. }
  46276. delete action._actionManager;
  46277. return true;
  46278. }
  46279. return false;
  46280. };
  46281. /**
  46282. * Process a specific trigger
  46283. * @param {number} trigger - the trigger to process
  46284. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46285. */
  46286. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46287. for (var index = 0; index < this.actions.length; index++) {
  46288. var action = this.actions[index];
  46289. if (action.trigger === trigger) {
  46290. if (evt) {
  46291. if (trigger === ActionManager.OnKeyUpTrigger
  46292. || trigger === ActionManager.OnKeyDownTrigger) {
  46293. var parameter = action.getTriggerParameter();
  46294. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46295. if (!parameter.toLowerCase) {
  46296. continue;
  46297. }
  46298. var lowerCase = parameter.toLowerCase();
  46299. if (lowerCase !== evt.sourceEvent.key) {
  46300. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46301. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46302. if (actualkey !== lowerCase) {
  46303. continue;
  46304. }
  46305. }
  46306. }
  46307. }
  46308. }
  46309. action._executeCurrent(evt);
  46310. }
  46311. }
  46312. };
  46313. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46314. var properties = propertyPath.split(".");
  46315. for (var index = 0; index < properties.length - 1; index++) {
  46316. target = target[properties[index]];
  46317. }
  46318. return target;
  46319. };
  46320. ActionManager.prototype._getProperty = function (propertyPath) {
  46321. var properties = propertyPath.split(".");
  46322. return properties[properties.length - 1];
  46323. };
  46324. ActionManager.prototype.serialize = function (name) {
  46325. var root = {
  46326. children: new Array(),
  46327. name: name,
  46328. type: 3,
  46329. properties: new Array() // Empty for root but required
  46330. };
  46331. for (var i = 0; i < this.actions.length; i++) {
  46332. var triggerObject = {
  46333. type: 0,
  46334. children: new Array(),
  46335. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46336. properties: new Array()
  46337. };
  46338. var triggerOptions = this.actions[i].triggerOptions;
  46339. if (triggerOptions && typeof triggerOptions !== "number") {
  46340. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46341. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46342. }
  46343. else {
  46344. var parameter = {};
  46345. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46346. if (triggerOptions.parameter.mesh) {
  46347. parameter._meshId = triggerOptions.parameter.mesh.id;
  46348. }
  46349. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46350. }
  46351. }
  46352. // Serialize child action, recursively
  46353. this.actions[i].serialize(triggerObject);
  46354. // Add serialized trigger
  46355. root.children.push(triggerObject);
  46356. }
  46357. return root;
  46358. };
  46359. ActionManager.Parse = function (parsedActions, object, scene) {
  46360. var actionManager = new ActionManager(scene);
  46361. if (object === null)
  46362. scene.actionManager = actionManager;
  46363. else
  46364. object.actionManager = actionManager;
  46365. // instanciate a new object
  46366. var instanciate = function (name, params) {
  46367. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  46368. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  46369. newInstance.constructor.apply(newInstance, params);
  46370. return newInstance;
  46371. };
  46372. var parseParameter = function (name, value, target, propertyPath) {
  46373. if (propertyPath === null) {
  46374. // String, boolean or float
  46375. var floatValue = parseFloat(value);
  46376. if (value === "true" || value === "false")
  46377. return value === "true";
  46378. else
  46379. return isNaN(floatValue) ? value : floatValue;
  46380. }
  46381. var effectiveTarget = propertyPath.split(".");
  46382. var values = value.split(",");
  46383. // Get effective Target
  46384. for (var i = 0; i < effectiveTarget.length; i++) {
  46385. target = target[effectiveTarget[i]];
  46386. }
  46387. // Return appropriate value with its type
  46388. if (typeof (target) === "boolean")
  46389. return values[0] === "true";
  46390. if (typeof (target) === "string")
  46391. return values[0];
  46392. // Parameters with multiple values such as Vector3 etc.
  46393. var split = new Array();
  46394. for (var i = 0; i < values.length; i++)
  46395. split.push(parseFloat(values[i]));
  46396. if (target instanceof BABYLON.Vector3)
  46397. return BABYLON.Vector3.FromArray(split);
  46398. if (target instanceof BABYLON.Vector4)
  46399. return BABYLON.Vector4.FromArray(split);
  46400. if (target instanceof BABYLON.Color3)
  46401. return BABYLON.Color3.FromArray(split);
  46402. if (target instanceof BABYLON.Color4)
  46403. return BABYLON.Color4.FromArray(split);
  46404. return parseFloat(values[0]);
  46405. };
  46406. // traverse graph per trigger
  46407. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46408. if (combineArray === void 0) { combineArray = null; }
  46409. if (parsedAction.detached)
  46410. return;
  46411. var parameters = new Array();
  46412. var target = null;
  46413. var propertyPath = null;
  46414. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46415. // Parameters
  46416. if (parsedAction.type === 2)
  46417. parameters.push(actionManager);
  46418. else
  46419. parameters.push(trigger);
  46420. if (combine) {
  46421. var actions = new Array();
  46422. for (var j = 0; j < parsedAction.combine.length; j++) {
  46423. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46424. }
  46425. parameters.push(actions);
  46426. }
  46427. else {
  46428. for (var i = 0; i < parsedAction.properties.length; i++) {
  46429. var value = parsedAction.properties[i].value;
  46430. var name = parsedAction.properties[i].name;
  46431. var targetType = parsedAction.properties[i].targetType;
  46432. if (name === "target")
  46433. if (targetType !== null && targetType === "SceneProperties")
  46434. value = target = scene;
  46435. else
  46436. value = target = scene.getNodeByName(value);
  46437. else if (name === "parent")
  46438. value = scene.getNodeByName(value);
  46439. else if (name === "sound")
  46440. value = scene.getSoundByName(value);
  46441. else if (name !== "propertyPath") {
  46442. if (parsedAction.type === 2 && name === "operator")
  46443. value = BABYLON.ValueCondition[value];
  46444. else
  46445. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46446. }
  46447. else {
  46448. propertyPath = value;
  46449. }
  46450. parameters.push(value);
  46451. }
  46452. }
  46453. if (combineArray === null) {
  46454. parameters.push(condition);
  46455. }
  46456. else {
  46457. parameters.push(null);
  46458. }
  46459. // If interpolate value action
  46460. if (parsedAction.name === "InterpolateValueAction") {
  46461. var param = parameters[parameters.length - 2];
  46462. parameters[parameters.length - 1] = param;
  46463. parameters[parameters.length - 2] = condition;
  46464. }
  46465. // Action or condition(s) and not CombineAction
  46466. var newAction = instanciate(parsedAction.name, parameters);
  46467. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46468. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46469. if (action)
  46470. action.then(nothing);
  46471. else
  46472. actionManager.registerAction(nothing);
  46473. action = nothing;
  46474. }
  46475. if (combineArray === null) {
  46476. if (newAction instanceof BABYLON.Condition) {
  46477. condition = newAction;
  46478. newAction = action;
  46479. }
  46480. else {
  46481. condition = null;
  46482. if (action)
  46483. action.then(newAction);
  46484. else
  46485. actionManager.registerAction(newAction);
  46486. }
  46487. }
  46488. else {
  46489. combineArray.push(newAction);
  46490. }
  46491. for (var i = 0; i < parsedAction.children.length; i++)
  46492. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46493. };
  46494. // triggers
  46495. for (var i = 0; i < parsedActions.children.length; i++) {
  46496. var triggerParams;
  46497. var trigger = parsedActions.children[i];
  46498. if (trigger.properties.length > 0) {
  46499. var param = trigger.properties[0].value;
  46500. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46501. if (value._meshId) {
  46502. value.mesh = scene.getMeshByID(value._meshId);
  46503. }
  46504. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  46505. }
  46506. else
  46507. triggerParams = ActionManager[trigger.name];
  46508. for (var j = 0; j < trigger.children.length; j++) {
  46509. if (!trigger.detached)
  46510. traverse(trigger.children[j], triggerParams, null, null);
  46511. }
  46512. }
  46513. };
  46514. ActionManager.GetTriggerName = function (trigger) {
  46515. switch (trigger) {
  46516. case 0: return "NothingTrigger";
  46517. case 1: return "OnPickTrigger";
  46518. case 2: return "OnLeftPickTrigger";
  46519. case 3: return "OnRightPickTrigger";
  46520. case 4: return "OnCenterPickTrigger";
  46521. case 5: return "OnPickDownTrigger";
  46522. case 6: return "OnPickUpTrigger";
  46523. case 7: return "OnLongPressTrigger";
  46524. case 8: return "OnPointerOverTrigger";
  46525. case 9: return "OnPointerOutTrigger";
  46526. case 10: return "OnEveryFrameTrigger";
  46527. case 11: return "OnIntersectionEnterTrigger";
  46528. case 12: return "OnIntersectionExitTrigger";
  46529. case 13: return "OnKeyDownTrigger";
  46530. case 14: return "OnKeyUpTrigger";
  46531. case 15: return "OnPickOutTrigger";
  46532. default: return "";
  46533. }
  46534. };
  46535. // Statics
  46536. ActionManager._NothingTrigger = 0;
  46537. ActionManager._OnPickTrigger = 1;
  46538. ActionManager._OnLeftPickTrigger = 2;
  46539. ActionManager._OnRightPickTrigger = 3;
  46540. ActionManager._OnCenterPickTrigger = 4;
  46541. ActionManager._OnPickDownTrigger = 5;
  46542. ActionManager._OnDoublePickTrigger = 6;
  46543. ActionManager._OnPickUpTrigger = 7;
  46544. ActionManager._OnLongPressTrigger = 8;
  46545. ActionManager._OnPointerOverTrigger = 9;
  46546. ActionManager._OnPointerOutTrigger = 10;
  46547. ActionManager._OnEveryFrameTrigger = 11;
  46548. ActionManager._OnIntersectionEnterTrigger = 12;
  46549. ActionManager._OnIntersectionExitTrigger = 13;
  46550. ActionManager._OnKeyDownTrigger = 14;
  46551. ActionManager._OnKeyUpTrigger = 15;
  46552. ActionManager._OnPickOutTrigger = 16;
  46553. ActionManager.Triggers = {};
  46554. return ActionManager;
  46555. }());
  46556. BABYLON.ActionManager = ActionManager;
  46557. })(BABYLON || (BABYLON = {}));
  46558. //# sourceMappingURL=babylon.actionManager.js.map
  46559. var BABYLON;
  46560. (function (BABYLON) {
  46561. var InterpolateValueAction = /** @class */ (function (_super) {
  46562. __extends(InterpolateValueAction, _super);
  46563. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46564. if (duration === void 0) { duration = 1000; }
  46565. var _this = _super.call(this, triggerOptions, condition) || this;
  46566. _this.propertyPath = propertyPath;
  46567. _this.value = value;
  46568. _this.duration = duration;
  46569. _this.stopOtherAnimations = stopOtherAnimations;
  46570. _this.onInterpolationDone = onInterpolationDone;
  46571. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  46572. _this._target = _this._effectiveTarget = target;
  46573. return _this;
  46574. }
  46575. InterpolateValueAction.prototype._prepare = function () {
  46576. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46577. this._property = this._getProperty(this.propertyPath);
  46578. };
  46579. InterpolateValueAction.prototype.execute = function () {
  46580. var _this = this;
  46581. var scene = this._actionManager.getScene();
  46582. var keys = [
  46583. {
  46584. frame: 0,
  46585. value: this._effectiveTarget[this._property]
  46586. }, {
  46587. frame: 100,
  46588. value: this.value
  46589. }
  46590. ];
  46591. var dataType;
  46592. if (typeof this.value === "number") {
  46593. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46594. }
  46595. else if (this.value instanceof BABYLON.Color3) {
  46596. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46597. }
  46598. else if (this.value instanceof BABYLON.Vector3) {
  46599. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46600. }
  46601. else if (this.value instanceof BABYLON.Matrix) {
  46602. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46603. }
  46604. else if (this.value instanceof BABYLON.Quaternion) {
  46605. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  46606. }
  46607. else {
  46608. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  46609. return;
  46610. }
  46611. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  46612. animation.setKeys(keys);
  46613. if (this.stopOtherAnimations) {
  46614. scene.stopAnimation(this._effectiveTarget);
  46615. }
  46616. var wrapper = function () {
  46617. _this.onInterpolationDoneObservable.notifyObservers(_this);
  46618. if (_this.onInterpolationDone) {
  46619. _this.onInterpolationDone();
  46620. }
  46621. };
  46622. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  46623. };
  46624. InterpolateValueAction.prototype.serialize = function (parent) {
  46625. return _super.prototype._serialize.call(this, {
  46626. name: "InterpolateValueAction",
  46627. properties: [
  46628. BABYLON.Action._GetTargetProperty(this._target),
  46629. { name: "propertyPath", value: this.propertyPath },
  46630. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46631. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  46632. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  46633. ]
  46634. }, parent);
  46635. };
  46636. return InterpolateValueAction;
  46637. }(BABYLON.Action));
  46638. BABYLON.InterpolateValueAction = InterpolateValueAction;
  46639. })(BABYLON || (BABYLON = {}));
  46640. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  46641. var BABYLON;
  46642. (function (BABYLON) {
  46643. var SwitchBooleanAction = /** @class */ (function (_super) {
  46644. __extends(SwitchBooleanAction, _super);
  46645. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  46646. var _this = _super.call(this, triggerOptions, condition) || this;
  46647. _this.propertyPath = propertyPath;
  46648. _this._target = _this._effectiveTarget = target;
  46649. return _this;
  46650. }
  46651. SwitchBooleanAction.prototype._prepare = function () {
  46652. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46653. this._property = this._getProperty(this.propertyPath);
  46654. };
  46655. SwitchBooleanAction.prototype.execute = function () {
  46656. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  46657. };
  46658. SwitchBooleanAction.prototype.serialize = function (parent) {
  46659. return _super.prototype._serialize.call(this, {
  46660. name: "SwitchBooleanAction",
  46661. properties: [
  46662. BABYLON.Action._GetTargetProperty(this._target),
  46663. { name: "propertyPath", value: this.propertyPath }
  46664. ]
  46665. }, parent);
  46666. };
  46667. return SwitchBooleanAction;
  46668. }(BABYLON.Action));
  46669. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  46670. var SetStateAction = /** @class */ (function (_super) {
  46671. __extends(SetStateAction, _super);
  46672. function SetStateAction(triggerOptions, target, value, condition) {
  46673. var _this = _super.call(this, triggerOptions, condition) || this;
  46674. _this.value = value;
  46675. _this._target = target;
  46676. return _this;
  46677. }
  46678. SetStateAction.prototype.execute = function () {
  46679. this._target.state = this.value;
  46680. };
  46681. SetStateAction.prototype.serialize = function (parent) {
  46682. return _super.prototype._serialize.call(this, {
  46683. name: "SetStateAction",
  46684. properties: [
  46685. BABYLON.Action._GetTargetProperty(this._target),
  46686. { name: "value", value: this.value }
  46687. ]
  46688. }, parent);
  46689. };
  46690. return SetStateAction;
  46691. }(BABYLON.Action));
  46692. BABYLON.SetStateAction = SetStateAction;
  46693. var SetValueAction = /** @class */ (function (_super) {
  46694. __extends(SetValueAction, _super);
  46695. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  46696. var _this = _super.call(this, triggerOptions, condition) || this;
  46697. _this.propertyPath = propertyPath;
  46698. _this.value = value;
  46699. _this._target = _this._effectiveTarget = target;
  46700. return _this;
  46701. }
  46702. SetValueAction.prototype._prepare = function () {
  46703. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46704. this._property = this._getProperty(this.propertyPath);
  46705. };
  46706. SetValueAction.prototype.execute = function () {
  46707. this._effectiveTarget[this._property] = this.value;
  46708. if (this._target.markAsDirty) {
  46709. this._target.markAsDirty(this._property);
  46710. }
  46711. };
  46712. SetValueAction.prototype.serialize = function (parent) {
  46713. return _super.prototype._serialize.call(this, {
  46714. name: "SetValueAction",
  46715. properties: [
  46716. BABYLON.Action._GetTargetProperty(this._target),
  46717. { name: "propertyPath", value: this.propertyPath },
  46718. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46719. ]
  46720. }, parent);
  46721. };
  46722. return SetValueAction;
  46723. }(BABYLON.Action));
  46724. BABYLON.SetValueAction = SetValueAction;
  46725. var IncrementValueAction = /** @class */ (function (_super) {
  46726. __extends(IncrementValueAction, _super);
  46727. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  46728. var _this = _super.call(this, triggerOptions, condition) || this;
  46729. _this.propertyPath = propertyPath;
  46730. _this.value = value;
  46731. _this._target = _this._effectiveTarget = target;
  46732. return _this;
  46733. }
  46734. IncrementValueAction.prototype._prepare = function () {
  46735. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46736. this._property = this._getProperty(this.propertyPath);
  46737. if (typeof this._effectiveTarget[this._property] !== "number") {
  46738. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  46739. }
  46740. };
  46741. IncrementValueAction.prototype.execute = function () {
  46742. this._effectiveTarget[this._property] += this.value;
  46743. if (this._target.markAsDirty) {
  46744. this._target.markAsDirty(this._property);
  46745. }
  46746. };
  46747. IncrementValueAction.prototype.serialize = function (parent) {
  46748. return _super.prototype._serialize.call(this, {
  46749. name: "IncrementValueAction",
  46750. properties: [
  46751. BABYLON.Action._GetTargetProperty(this._target),
  46752. { name: "propertyPath", value: this.propertyPath },
  46753. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46754. ]
  46755. }, parent);
  46756. };
  46757. return IncrementValueAction;
  46758. }(BABYLON.Action));
  46759. BABYLON.IncrementValueAction = IncrementValueAction;
  46760. var PlayAnimationAction = /** @class */ (function (_super) {
  46761. __extends(PlayAnimationAction, _super);
  46762. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  46763. var _this = _super.call(this, triggerOptions, condition) || this;
  46764. _this.from = from;
  46765. _this.to = to;
  46766. _this.loop = loop;
  46767. _this._target = target;
  46768. return _this;
  46769. }
  46770. PlayAnimationAction.prototype._prepare = function () {
  46771. };
  46772. PlayAnimationAction.prototype.execute = function () {
  46773. var scene = this._actionManager.getScene();
  46774. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  46775. };
  46776. PlayAnimationAction.prototype.serialize = function (parent) {
  46777. return _super.prototype._serialize.call(this, {
  46778. name: "PlayAnimationAction",
  46779. properties: [
  46780. BABYLON.Action._GetTargetProperty(this._target),
  46781. { name: "from", value: String(this.from) },
  46782. { name: "to", value: String(this.to) },
  46783. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  46784. ]
  46785. }, parent);
  46786. };
  46787. return PlayAnimationAction;
  46788. }(BABYLON.Action));
  46789. BABYLON.PlayAnimationAction = PlayAnimationAction;
  46790. var StopAnimationAction = /** @class */ (function (_super) {
  46791. __extends(StopAnimationAction, _super);
  46792. function StopAnimationAction(triggerOptions, target, condition) {
  46793. var _this = _super.call(this, triggerOptions, condition) || this;
  46794. _this._target = target;
  46795. return _this;
  46796. }
  46797. StopAnimationAction.prototype._prepare = function () {
  46798. };
  46799. StopAnimationAction.prototype.execute = function () {
  46800. var scene = this._actionManager.getScene();
  46801. scene.stopAnimation(this._target);
  46802. };
  46803. StopAnimationAction.prototype.serialize = function (parent) {
  46804. return _super.prototype._serialize.call(this, {
  46805. name: "StopAnimationAction",
  46806. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  46807. }, parent);
  46808. };
  46809. return StopAnimationAction;
  46810. }(BABYLON.Action));
  46811. BABYLON.StopAnimationAction = StopAnimationAction;
  46812. var DoNothingAction = /** @class */ (function (_super) {
  46813. __extends(DoNothingAction, _super);
  46814. function DoNothingAction(triggerOptions, condition) {
  46815. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  46816. return _super.call(this, triggerOptions, condition) || this;
  46817. }
  46818. DoNothingAction.prototype.execute = function () {
  46819. };
  46820. DoNothingAction.prototype.serialize = function (parent) {
  46821. return _super.prototype._serialize.call(this, {
  46822. name: "DoNothingAction",
  46823. properties: []
  46824. }, parent);
  46825. };
  46826. return DoNothingAction;
  46827. }(BABYLON.Action));
  46828. BABYLON.DoNothingAction = DoNothingAction;
  46829. var CombineAction = /** @class */ (function (_super) {
  46830. __extends(CombineAction, _super);
  46831. function CombineAction(triggerOptions, children, condition) {
  46832. var _this = _super.call(this, triggerOptions, condition) || this;
  46833. _this.children = children;
  46834. return _this;
  46835. }
  46836. CombineAction.prototype._prepare = function () {
  46837. for (var index = 0; index < this.children.length; index++) {
  46838. this.children[index]._actionManager = this._actionManager;
  46839. this.children[index]._prepare();
  46840. }
  46841. };
  46842. CombineAction.prototype.execute = function (evt) {
  46843. for (var index = 0; index < this.children.length; index++) {
  46844. this.children[index].execute(evt);
  46845. }
  46846. };
  46847. CombineAction.prototype.serialize = function (parent) {
  46848. var serializationObject = _super.prototype._serialize.call(this, {
  46849. name: "CombineAction",
  46850. properties: [],
  46851. combine: []
  46852. }, parent);
  46853. for (var i = 0; i < this.children.length; i++) {
  46854. serializationObject.combine.push(this.children[i].serialize(null));
  46855. }
  46856. return serializationObject;
  46857. };
  46858. return CombineAction;
  46859. }(BABYLON.Action));
  46860. BABYLON.CombineAction = CombineAction;
  46861. var ExecuteCodeAction = /** @class */ (function (_super) {
  46862. __extends(ExecuteCodeAction, _super);
  46863. function ExecuteCodeAction(triggerOptions, func, condition) {
  46864. var _this = _super.call(this, triggerOptions, condition) || this;
  46865. _this.func = func;
  46866. return _this;
  46867. }
  46868. ExecuteCodeAction.prototype.execute = function (evt) {
  46869. this.func(evt);
  46870. };
  46871. return ExecuteCodeAction;
  46872. }(BABYLON.Action));
  46873. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  46874. var SetParentAction = /** @class */ (function (_super) {
  46875. __extends(SetParentAction, _super);
  46876. function SetParentAction(triggerOptions, target, parent, condition) {
  46877. var _this = _super.call(this, triggerOptions, condition) || this;
  46878. _this._target = target;
  46879. _this._parent = parent;
  46880. return _this;
  46881. }
  46882. SetParentAction.prototype._prepare = function () {
  46883. };
  46884. SetParentAction.prototype.execute = function () {
  46885. if (this._target.parent === this._parent) {
  46886. return;
  46887. }
  46888. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  46889. invertParentWorldMatrix.invert();
  46890. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  46891. this._target.parent = this._parent;
  46892. };
  46893. SetParentAction.prototype.serialize = function (parent) {
  46894. return _super.prototype._serialize.call(this, {
  46895. name: "SetParentAction",
  46896. properties: [
  46897. BABYLON.Action._GetTargetProperty(this._target),
  46898. BABYLON.Action._GetTargetProperty(this._parent),
  46899. ]
  46900. }, parent);
  46901. };
  46902. return SetParentAction;
  46903. }(BABYLON.Action));
  46904. BABYLON.SetParentAction = SetParentAction;
  46905. var PlaySoundAction = /** @class */ (function (_super) {
  46906. __extends(PlaySoundAction, _super);
  46907. function PlaySoundAction(triggerOptions, sound, condition) {
  46908. var _this = _super.call(this, triggerOptions, condition) || this;
  46909. _this._sound = sound;
  46910. return _this;
  46911. }
  46912. PlaySoundAction.prototype._prepare = function () {
  46913. };
  46914. PlaySoundAction.prototype.execute = function () {
  46915. if (this._sound !== undefined)
  46916. this._sound.play();
  46917. };
  46918. PlaySoundAction.prototype.serialize = function (parent) {
  46919. return _super.prototype._serialize.call(this, {
  46920. name: "PlaySoundAction",
  46921. properties: [{ name: "sound", value: this._sound.name }]
  46922. }, parent);
  46923. };
  46924. return PlaySoundAction;
  46925. }(BABYLON.Action));
  46926. BABYLON.PlaySoundAction = PlaySoundAction;
  46927. var StopSoundAction = /** @class */ (function (_super) {
  46928. __extends(StopSoundAction, _super);
  46929. function StopSoundAction(triggerOptions, sound, condition) {
  46930. var _this = _super.call(this, triggerOptions, condition) || this;
  46931. _this._sound = sound;
  46932. return _this;
  46933. }
  46934. StopSoundAction.prototype._prepare = function () {
  46935. };
  46936. StopSoundAction.prototype.execute = function () {
  46937. if (this._sound !== undefined)
  46938. this._sound.stop();
  46939. };
  46940. StopSoundAction.prototype.serialize = function (parent) {
  46941. return _super.prototype._serialize.call(this, {
  46942. name: "StopSoundAction",
  46943. properties: [{ name: "sound", value: this._sound.name }]
  46944. }, parent);
  46945. };
  46946. return StopSoundAction;
  46947. }(BABYLON.Action));
  46948. BABYLON.StopSoundAction = StopSoundAction;
  46949. })(BABYLON || (BABYLON = {}));
  46950. //# sourceMappingURL=babylon.directActions.js.map
  46951. var BABYLON;
  46952. (function (BABYLON) {
  46953. var SpriteManager = /** @class */ (function () {
  46954. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  46955. if (epsilon === void 0) { epsilon = 0.01; }
  46956. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46957. this.name = name;
  46958. this.sprites = new Array();
  46959. this.renderingGroupId = 0;
  46960. this.layerMask = 0x0FFFFFFF;
  46961. this.fogEnabled = true;
  46962. this.isPickable = false;
  46963. /**
  46964. * An event triggered when the manager is disposed.
  46965. * @type {BABYLON.Observable}
  46966. */
  46967. this.onDisposeObservable = new BABYLON.Observable();
  46968. this._vertexBuffers = {};
  46969. this._capacity = capacity;
  46970. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  46971. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46972. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46973. if (cellSize.width && cellSize.height) {
  46974. this.cellWidth = cellSize.width;
  46975. this.cellHeight = cellSize.height;
  46976. }
  46977. else if (cellSize !== undefined) {
  46978. this.cellWidth = cellSize;
  46979. this.cellHeight = cellSize;
  46980. }
  46981. else {
  46982. return;
  46983. }
  46984. this._epsilon = epsilon;
  46985. this._scene = scene;
  46986. this._scene.spriteManagers.push(this);
  46987. var indices = [];
  46988. var index = 0;
  46989. for (var count = 0; count < capacity; count++) {
  46990. indices.push(index);
  46991. indices.push(index + 1);
  46992. indices.push(index + 2);
  46993. indices.push(index);
  46994. indices.push(index + 2);
  46995. indices.push(index + 3);
  46996. index += 4;
  46997. }
  46998. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  46999. // VBO
  47000. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  47001. this._vertexData = new Float32Array(capacity * 16 * 4);
  47002. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  47003. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  47004. var options = this._buffer.createVertexBuffer("options", 4, 4);
  47005. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  47006. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  47007. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  47008. this._vertexBuffers["options"] = options;
  47009. this._vertexBuffers["cellInfo"] = cellInfo;
  47010. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  47011. // Effects
  47012. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  47013. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  47014. }
  47015. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  47016. set: function (callback) {
  47017. if (this._onDisposeObserver) {
  47018. this.onDisposeObservable.remove(this._onDisposeObserver);
  47019. }
  47020. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  47021. },
  47022. enumerable: true,
  47023. configurable: true
  47024. });
  47025. Object.defineProperty(SpriteManager.prototype, "texture", {
  47026. get: function () {
  47027. return this._spriteTexture;
  47028. },
  47029. set: function (value) {
  47030. this._spriteTexture = value;
  47031. },
  47032. enumerable: true,
  47033. configurable: true
  47034. });
  47035. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  47036. var arrayOffset = index * 16;
  47037. if (offsetX === 0)
  47038. offsetX = this._epsilon;
  47039. else if (offsetX === 1)
  47040. offsetX = 1 - this._epsilon;
  47041. if (offsetY === 0)
  47042. offsetY = this._epsilon;
  47043. else if (offsetY === 1)
  47044. offsetY = 1 - this._epsilon;
  47045. this._vertexData[arrayOffset] = sprite.position.x;
  47046. this._vertexData[arrayOffset + 1] = sprite.position.y;
  47047. this._vertexData[arrayOffset + 2] = sprite.position.z;
  47048. this._vertexData[arrayOffset + 3] = sprite.angle;
  47049. this._vertexData[arrayOffset + 4] = sprite.width;
  47050. this._vertexData[arrayOffset + 5] = sprite.height;
  47051. this._vertexData[arrayOffset + 6] = offsetX;
  47052. this._vertexData[arrayOffset + 7] = offsetY;
  47053. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  47054. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  47055. var offset = (sprite.cellIndex / rowSize) >> 0;
  47056. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  47057. this._vertexData[arrayOffset + 11] = offset;
  47058. // Color
  47059. this._vertexData[arrayOffset + 12] = sprite.color.r;
  47060. this._vertexData[arrayOffset + 13] = sprite.color.g;
  47061. this._vertexData[arrayOffset + 14] = sprite.color.b;
  47062. this._vertexData[arrayOffset + 15] = sprite.color.a;
  47063. };
  47064. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  47065. var count = Math.min(this._capacity, this.sprites.length);
  47066. var min = BABYLON.Vector3.Zero();
  47067. var max = BABYLON.Vector3.Zero();
  47068. var distance = Number.MAX_VALUE;
  47069. var currentSprite = null;
  47070. var cameraSpacePosition = BABYLON.Vector3.Zero();
  47071. var cameraView = camera.getViewMatrix();
  47072. for (var index = 0; index < count; index++) {
  47073. var sprite = this.sprites[index];
  47074. if (!sprite) {
  47075. continue;
  47076. }
  47077. if (predicate) {
  47078. if (!predicate(sprite)) {
  47079. continue;
  47080. }
  47081. }
  47082. else if (!sprite.isPickable) {
  47083. continue;
  47084. }
  47085. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  47086. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  47087. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  47088. if (ray.intersectsBoxMinMax(min, max)) {
  47089. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  47090. if (distance > currentDistance) {
  47091. distance = currentDistance;
  47092. currentSprite = sprite;
  47093. if (fastCheck) {
  47094. break;
  47095. }
  47096. }
  47097. }
  47098. }
  47099. if (currentSprite) {
  47100. var result = new BABYLON.PickingInfo();
  47101. result.hit = true;
  47102. result.pickedSprite = currentSprite;
  47103. result.distance = distance;
  47104. return result;
  47105. }
  47106. return null;
  47107. };
  47108. SpriteManager.prototype.render = function () {
  47109. // Check
  47110. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  47111. return;
  47112. var engine = this._scene.getEngine();
  47113. var baseSize = this._spriteTexture.getBaseSize();
  47114. // Sprites
  47115. var deltaTime = engine.getDeltaTime();
  47116. var max = Math.min(this._capacity, this.sprites.length);
  47117. var rowSize = baseSize.width / this.cellWidth;
  47118. var offset = 0;
  47119. for (var index = 0; index < max; index++) {
  47120. var sprite = this.sprites[index];
  47121. if (!sprite) {
  47122. continue;
  47123. }
  47124. sprite._animate(deltaTime);
  47125. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  47126. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  47127. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  47128. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  47129. }
  47130. this._buffer.update(this._vertexData);
  47131. // Render
  47132. var effect = this._effectBase;
  47133. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  47134. effect = this._effectFog;
  47135. }
  47136. engine.enableEffect(effect);
  47137. var viewMatrix = this._scene.getViewMatrix();
  47138. effect.setTexture("diffuseSampler", this._spriteTexture);
  47139. effect.setMatrix("view", viewMatrix);
  47140. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  47141. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  47142. // Fog
  47143. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  47144. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  47145. effect.setColor3("vFogColor", this._scene.fogColor);
  47146. }
  47147. // VBOs
  47148. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  47149. // Draw order
  47150. engine.setDepthFunctionToLessOrEqual();
  47151. effect.setBool("alphaTest", true);
  47152. engine.setColorWrite(false);
  47153. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  47154. engine.setColorWrite(true);
  47155. effect.setBool("alphaTest", false);
  47156. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47157. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  47158. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47159. };
  47160. SpriteManager.prototype.dispose = function () {
  47161. if (this._buffer) {
  47162. this._buffer.dispose();
  47163. this._buffer = null;
  47164. }
  47165. if (this._indexBuffer) {
  47166. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47167. this._indexBuffer = null;
  47168. }
  47169. if (this._spriteTexture) {
  47170. this._spriteTexture.dispose();
  47171. this._spriteTexture = null;
  47172. }
  47173. // Remove from scene
  47174. var index = this._scene.spriteManagers.indexOf(this);
  47175. this._scene.spriteManagers.splice(index, 1);
  47176. // Callback
  47177. this.onDisposeObservable.notifyObservers(this);
  47178. this.onDisposeObservable.clear();
  47179. };
  47180. return SpriteManager;
  47181. }());
  47182. BABYLON.SpriteManager = SpriteManager;
  47183. })(BABYLON || (BABYLON = {}));
  47184. //# sourceMappingURL=babylon.spriteManager.js.map
  47185. var BABYLON;
  47186. (function (BABYLON) {
  47187. var Sprite = /** @class */ (function () {
  47188. function Sprite(name, manager) {
  47189. this.name = name;
  47190. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47191. this.width = 1.0;
  47192. this.height = 1.0;
  47193. this.angle = 0;
  47194. this.cellIndex = 0;
  47195. this.invertU = 0;
  47196. this.invertV = 0;
  47197. this.animations = new Array();
  47198. this.isPickable = false;
  47199. this._animationStarted = false;
  47200. this._loopAnimation = false;
  47201. this._fromIndex = 0;
  47202. this._toIndex = 0;
  47203. this._delay = 0;
  47204. this._direction = 1;
  47205. this._time = 0;
  47206. this._manager = manager;
  47207. this._manager.sprites.push(this);
  47208. this.position = BABYLON.Vector3.Zero();
  47209. }
  47210. Object.defineProperty(Sprite.prototype, "size", {
  47211. get: function () {
  47212. return this.width;
  47213. },
  47214. set: function (value) {
  47215. this.width = value;
  47216. this.height = value;
  47217. },
  47218. enumerable: true,
  47219. configurable: true
  47220. });
  47221. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  47222. this._fromIndex = from;
  47223. this._toIndex = to;
  47224. this._loopAnimation = loop;
  47225. this._delay = delay;
  47226. this._animationStarted = true;
  47227. this._direction = from < to ? 1 : -1;
  47228. this.cellIndex = from;
  47229. this._time = 0;
  47230. this._onAnimationEnd = onAnimationEnd;
  47231. };
  47232. Sprite.prototype.stopAnimation = function () {
  47233. this._animationStarted = false;
  47234. };
  47235. Sprite.prototype._animate = function (deltaTime) {
  47236. if (!this._animationStarted)
  47237. return;
  47238. this._time += deltaTime;
  47239. if (this._time > this._delay) {
  47240. this._time = this._time % this._delay;
  47241. this.cellIndex += this._direction;
  47242. if (this.cellIndex > this._toIndex) {
  47243. if (this._loopAnimation) {
  47244. this.cellIndex = this._fromIndex;
  47245. }
  47246. else {
  47247. this.cellIndex = this._toIndex;
  47248. this._animationStarted = false;
  47249. if (this._onAnimationEnd) {
  47250. this._onAnimationEnd();
  47251. }
  47252. if (this.disposeWhenFinishedAnimating) {
  47253. this.dispose();
  47254. }
  47255. }
  47256. }
  47257. }
  47258. };
  47259. Sprite.prototype.dispose = function () {
  47260. for (var i = 0; i < this._manager.sprites.length; i++) {
  47261. if (this._manager.sprites[i] == this) {
  47262. this._manager.sprites.splice(i, 1);
  47263. }
  47264. }
  47265. };
  47266. return Sprite;
  47267. }());
  47268. BABYLON.Sprite = Sprite;
  47269. })(BABYLON || (BABYLON = {}));
  47270. //# sourceMappingURL=babylon.sprite.js.map
  47271. var BABYLON;
  47272. (function (BABYLON) {
  47273. var IntersectionInfo = /** @class */ (function () {
  47274. function IntersectionInfo(bu, bv, distance) {
  47275. this.bu = bu;
  47276. this.bv = bv;
  47277. this.distance = distance;
  47278. this.faceId = 0;
  47279. this.subMeshId = 0;
  47280. }
  47281. return IntersectionInfo;
  47282. }());
  47283. BABYLON.IntersectionInfo = IntersectionInfo;
  47284. var PickingInfo = /** @class */ (function () {
  47285. function PickingInfo() {
  47286. this.hit = false;
  47287. this.distance = 0;
  47288. this.pickedPoint = null;
  47289. this.pickedMesh = null;
  47290. this.bu = 0;
  47291. this.bv = 0;
  47292. this.faceId = -1;
  47293. this.subMeshId = 0;
  47294. this.pickedSprite = null;
  47295. }
  47296. // Methods
  47297. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  47298. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  47299. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  47300. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  47301. return null;
  47302. }
  47303. var indices = this.pickedMesh.getIndices();
  47304. if (!indices) {
  47305. return null;
  47306. }
  47307. var result;
  47308. if (useVerticesNormals) {
  47309. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47310. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  47311. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  47312. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  47313. normal0 = normal0.scale(this.bu);
  47314. normal1 = normal1.scale(this.bv);
  47315. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  47316. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  47317. }
  47318. else {
  47319. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47320. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  47321. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  47322. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  47323. var p1p2 = vertex1.subtract(vertex2);
  47324. var p3p2 = vertex3.subtract(vertex2);
  47325. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  47326. }
  47327. if (useWorldCoordinates) {
  47328. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  47329. }
  47330. return BABYLON.Vector3.Normalize(result);
  47331. };
  47332. PickingInfo.prototype.getTextureCoordinates = function () {
  47333. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47334. return null;
  47335. }
  47336. var indices = this.pickedMesh.getIndices();
  47337. if (!indices) {
  47338. return null;
  47339. }
  47340. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47341. if (!uvs) {
  47342. return null;
  47343. }
  47344. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  47345. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  47346. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  47347. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  47348. uv1 = uv1.scale(this.bu);
  47349. uv2 = uv2.scale(this.bv);
  47350. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  47351. };
  47352. return PickingInfo;
  47353. }());
  47354. BABYLON.PickingInfo = PickingInfo;
  47355. })(BABYLON || (BABYLON = {}));
  47356. //# sourceMappingURL=babylon.pickingInfo.js.map
  47357. var BABYLON;
  47358. (function (BABYLON) {
  47359. var Ray = /** @class */ (function () {
  47360. function Ray(origin, direction, length) {
  47361. if (length === void 0) { length = Number.MAX_VALUE; }
  47362. this.origin = origin;
  47363. this.direction = direction;
  47364. this.length = length;
  47365. }
  47366. // Methods
  47367. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  47368. var d = 0.0;
  47369. var maxValue = Number.MAX_VALUE;
  47370. var inv;
  47371. var min;
  47372. var max;
  47373. var temp;
  47374. if (Math.abs(this.direction.x) < 0.0000001) {
  47375. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  47376. return false;
  47377. }
  47378. }
  47379. else {
  47380. inv = 1.0 / this.direction.x;
  47381. min = (minimum.x - this.origin.x) * inv;
  47382. max = (maximum.x - this.origin.x) * inv;
  47383. if (max === -Infinity) {
  47384. max = Infinity;
  47385. }
  47386. if (min > max) {
  47387. temp = min;
  47388. min = max;
  47389. max = temp;
  47390. }
  47391. d = Math.max(min, d);
  47392. maxValue = Math.min(max, maxValue);
  47393. if (d > maxValue) {
  47394. return false;
  47395. }
  47396. }
  47397. if (Math.abs(this.direction.y) < 0.0000001) {
  47398. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  47399. return false;
  47400. }
  47401. }
  47402. else {
  47403. inv = 1.0 / this.direction.y;
  47404. min = (minimum.y - this.origin.y) * inv;
  47405. max = (maximum.y - this.origin.y) * inv;
  47406. if (max === -Infinity) {
  47407. max = Infinity;
  47408. }
  47409. if (min > max) {
  47410. temp = min;
  47411. min = max;
  47412. max = temp;
  47413. }
  47414. d = Math.max(min, d);
  47415. maxValue = Math.min(max, maxValue);
  47416. if (d > maxValue) {
  47417. return false;
  47418. }
  47419. }
  47420. if (Math.abs(this.direction.z) < 0.0000001) {
  47421. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  47422. return false;
  47423. }
  47424. }
  47425. else {
  47426. inv = 1.0 / this.direction.z;
  47427. min = (minimum.z - this.origin.z) * inv;
  47428. max = (maximum.z - this.origin.z) * inv;
  47429. if (max === -Infinity) {
  47430. max = Infinity;
  47431. }
  47432. if (min > max) {
  47433. temp = min;
  47434. min = max;
  47435. max = temp;
  47436. }
  47437. d = Math.max(min, d);
  47438. maxValue = Math.min(max, maxValue);
  47439. if (d > maxValue) {
  47440. return false;
  47441. }
  47442. }
  47443. return true;
  47444. };
  47445. Ray.prototype.intersectsBox = function (box) {
  47446. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  47447. };
  47448. Ray.prototype.intersectsSphere = function (sphere) {
  47449. var x = sphere.center.x - this.origin.x;
  47450. var y = sphere.center.y - this.origin.y;
  47451. var z = sphere.center.z - this.origin.z;
  47452. var pyth = (x * x) + (y * y) + (z * z);
  47453. var rr = sphere.radius * sphere.radius;
  47454. if (pyth <= rr) {
  47455. return true;
  47456. }
  47457. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  47458. if (dot < 0.0) {
  47459. return false;
  47460. }
  47461. var temp = pyth - (dot * dot);
  47462. return temp <= rr;
  47463. };
  47464. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  47465. if (!this._edge1) {
  47466. this._edge1 = BABYLON.Vector3.Zero();
  47467. this._edge2 = BABYLON.Vector3.Zero();
  47468. this._pvec = BABYLON.Vector3.Zero();
  47469. this._tvec = BABYLON.Vector3.Zero();
  47470. this._qvec = BABYLON.Vector3.Zero();
  47471. }
  47472. vertex1.subtractToRef(vertex0, this._edge1);
  47473. vertex2.subtractToRef(vertex0, this._edge2);
  47474. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  47475. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  47476. if (det === 0) {
  47477. return null;
  47478. }
  47479. var invdet = 1 / det;
  47480. this.origin.subtractToRef(vertex0, this._tvec);
  47481. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  47482. if (bu < 0 || bu > 1.0) {
  47483. return null;
  47484. }
  47485. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  47486. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  47487. if (bv < 0 || bu + bv > 1.0) {
  47488. return null;
  47489. }
  47490. //check if the distance is longer than the predefined length.
  47491. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  47492. if (distance > this.length) {
  47493. return null;
  47494. }
  47495. return new BABYLON.IntersectionInfo(bu, bv, distance);
  47496. };
  47497. Ray.prototype.intersectsPlane = function (plane) {
  47498. var distance;
  47499. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  47500. if (Math.abs(result1) < 9.99999997475243E-07) {
  47501. return null;
  47502. }
  47503. else {
  47504. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  47505. distance = (-plane.d - result2) / result1;
  47506. if (distance < 0.0) {
  47507. if (distance < -9.99999997475243E-07) {
  47508. return null;
  47509. }
  47510. else {
  47511. return 0;
  47512. }
  47513. }
  47514. return distance;
  47515. }
  47516. };
  47517. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  47518. var tm = BABYLON.Tmp.Matrix[0];
  47519. mesh.getWorldMatrix().invertToRef(tm);
  47520. if (this._tmpRay) {
  47521. Ray.TransformToRef(this, tm, this._tmpRay);
  47522. }
  47523. else {
  47524. this._tmpRay = Ray.Transform(this, tm);
  47525. }
  47526. return mesh.intersects(this._tmpRay, fastCheck);
  47527. };
  47528. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  47529. if (results) {
  47530. results.length = 0;
  47531. }
  47532. else {
  47533. results = [];
  47534. }
  47535. for (var i = 0; i < meshes.length; i++) {
  47536. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  47537. if (pickInfo.hit) {
  47538. results.push(pickInfo);
  47539. }
  47540. }
  47541. results.sort(this._comparePickingInfo);
  47542. return results;
  47543. };
  47544. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  47545. if (pickingInfoA.distance < pickingInfoB.distance) {
  47546. return -1;
  47547. }
  47548. else if (pickingInfoA.distance > pickingInfoB.distance) {
  47549. return 1;
  47550. }
  47551. else {
  47552. return 0;
  47553. }
  47554. };
  47555. /**
  47556. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  47557. * @param sega the first point of the segment to test the intersection against
  47558. * @param segb the second point of the segment to test the intersection against
  47559. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  47560. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  47561. */
  47562. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  47563. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  47564. var u = segb.subtract(sega);
  47565. var v = rsegb.subtract(this.origin);
  47566. var w = sega.subtract(this.origin);
  47567. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  47568. var b = BABYLON.Vector3.Dot(u, v);
  47569. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  47570. var d = BABYLON.Vector3.Dot(u, w);
  47571. var e = BABYLON.Vector3.Dot(v, w);
  47572. var D = a * c - b * b; // always >= 0
  47573. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  47574. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  47575. // compute the line parameters of the two closest points
  47576. if (D < Ray.smallnum) {
  47577. sN = 0.0; // force using point P0 on segment S1
  47578. sD = 1.0; // to prevent possible division by 0.0 later
  47579. tN = e;
  47580. tD = c;
  47581. }
  47582. else {
  47583. sN = (b * e - c * d);
  47584. tN = (a * e - b * d);
  47585. if (sN < 0.0) {
  47586. sN = 0.0;
  47587. tN = e;
  47588. tD = c;
  47589. }
  47590. else if (sN > sD) {
  47591. sN = sD;
  47592. tN = e + b;
  47593. tD = c;
  47594. }
  47595. }
  47596. if (tN < 0.0) {
  47597. tN = 0.0;
  47598. // recompute sc for this edge
  47599. if (-d < 0.0) {
  47600. sN = 0.0;
  47601. }
  47602. else if (-d > a)
  47603. sN = sD;
  47604. else {
  47605. sN = -d;
  47606. sD = a;
  47607. }
  47608. }
  47609. else if (tN > tD) {
  47610. tN = tD;
  47611. // recompute sc for this edge
  47612. if ((-d + b) < 0.0) {
  47613. sN = 0;
  47614. }
  47615. else if ((-d + b) > a) {
  47616. sN = sD;
  47617. }
  47618. else {
  47619. sN = (-d + b);
  47620. sD = a;
  47621. }
  47622. }
  47623. // finally do the division to get sc and tc
  47624. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  47625. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  47626. // get the difference of the two closest points
  47627. var qtc = v.multiplyByFloats(tc, tc, tc);
  47628. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  47629. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  47630. if (isIntersected) {
  47631. return qtc.length();
  47632. }
  47633. return -1;
  47634. };
  47635. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47636. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  47637. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  47638. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  47639. this.direction.normalize();
  47640. return this;
  47641. };
  47642. // Statics
  47643. Ray.Zero = function () {
  47644. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  47645. };
  47646. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47647. var result = Ray.Zero();
  47648. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  47649. };
  47650. /**
  47651. * 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
  47652. * transformed to the given world matrix.
  47653. * @param origin The origin point
  47654. * @param end The end point
  47655. * @param world a matrix to transform the ray to. Default is the identity matrix.
  47656. */
  47657. Ray.CreateNewFromTo = function (origin, end, world) {
  47658. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  47659. var direction = end.subtract(origin);
  47660. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  47661. direction.normalize();
  47662. return Ray.Transform(new Ray(origin, direction, length), world);
  47663. };
  47664. Ray.Transform = function (ray, matrix) {
  47665. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  47666. Ray.TransformToRef(ray, matrix, result);
  47667. return result;
  47668. };
  47669. Ray.TransformToRef = function (ray, matrix, result) {
  47670. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  47671. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  47672. result.length = ray.length;
  47673. var dir = result.direction;
  47674. var len = dir.length();
  47675. if (!(len === 0 || len === 1)) {
  47676. var num = 1.0 / len;
  47677. dir.x *= num;
  47678. dir.y *= num;
  47679. dir.z *= num;
  47680. result.length *= len;
  47681. }
  47682. };
  47683. Ray.smallnum = 0.00000001;
  47684. Ray.rayl = 10e8;
  47685. return Ray;
  47686. }());
  47687. BABYLON.Ray = Ray;
  47688. })(BABYLON || (BABYLON = {}));
  47689. //# sourceMappingURL=babylon.ray.js.map
  47690. var BABYLON;
  47691. (function (BABYLON) {
  47692. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  47693. if (boxMin.x > sphereCenter.x + sphereRadius)
  47694. return false;
  47695. if (sphereCenter.x - sphereRadius > boxMax.x)
  47696. return false;
  47697. if (boxMin.y > sphereCenter.y + sphereRadius)
  47698. return false;
  47699. if (sphereCenter.y - sphereRadius > boxMax.y)
  47700. return false;
  47701. if (boxMin.z > sphereCenter.z + sphereRadius)
  47702. return false;
  47703. if (sphereCenter.z - sphereRadius > boxMax.z)
  47704. return false;
  47705. return true;
  47706. };
  47707. var getLowestRoot = (function () {
  47708. var result = { root: 0, found: false };
  47709. return function (a, b, c, maxR) {
  47710. result.root = 0;
  47711. result.found = false;
  47712. var determinant = b * b - 4.0 * a * c;
  47713. if (determinant < 0)
  47714. return result;
  47715. var sqrtD = Math.sqrt(determinant);
  47716. var r1 = (-b - sqrtD) / (2.0 * a);
  47717. var r2 = (-b + sqrtD) / (2.0 * a);
  47718. if (r1 > r2) {
  47719. var temp = r2;
  47720. r2 = r1;
  47721. r1 = temp;
  47722. }
  47723. if (r1 > 0 && r1 < maxR) {
  47724. result.root = r1;
  47725. result.found = true;
  47726. return result;
  47727. }
  47728. if (r2 > 0 && r2 < maxR) {
  47729. result.root = r2;
  47730. result.found = true;
  47731. return result;
  47732. }
  47733. return result;
  47734. };
  47735. })();
  47736. var Collider = /** @class */ (function () {
  47737. function Collider() {
  47738. this._collisionPoint = BABYLON.Vector3.Zero();
  47739. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  47740. this._tempVector = BABYLON.Vector3.Zero();
  47741. this._tempVector2 = BABYLON.Vector3.Zero();
  47742. this._tempVector3 = BABYLON.Vector3.Zero();
  47743. this._tempVector4 = BABYLON.Vector3.Zero();
  47744. this._edge = BABYLON.Vector3.Zero();
  47745. this._baseToVertex = BABYLON.Vector3.Zero();
  47746. this._destinationPoint = BABYLON.Vector3.Zero();
  47747. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  47748. this._displacementVector = BABYLON.Vector3.Zero();
  47749. this._radius = BABYLON.Vector3.One();
  47750. this._retry = 0;
  47751. this._basePointWorld = BABYLON.Vector3.Zero();
  47752. this._velocityWorld = BABYLON.Vector3.Zero();
  47753. this._normalizedVelocity = BABYLON.Vector3.Zero();
  47754. this._collisionMask = -1;
  47755. }
  47756. Object.defineProperty(Collider.prototype, "collisionMask", {
  47757. get: function () {
  47758. return this._collisionMask;
  47759. },
  47760. set: function (mask) {
  47761. this._collisionMask = !isNaN(mask) ? mask : -1;
  47762. },
  47763. enumerable: true,
  47764. configurable: true
  47765. });
  47766. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  47767. /**
  47768. * Gets the plane normal used to compute the sliding response (in local space)
  47769. */
  47770. get: function () {
  47771. return this._slidePlaneNormal;
  47772. },
  47773. enumerable: true,
  47774. configurable: true
  47775. });
  47776. // Methods
  47777. Collider.prototype._initialize = function (source, dir, e) {
  47778. this._velocity = dir;
  47779. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  47780. this._basePoint = source;
  47781. source.multiplyToRef(this._radius, this._basePointWorld);
  47782. dir.multiplyToRef(this._radius, this._velocityWorld);
  47783. this._velocityWorldLength = this._velocityWorld.length();
  47784. this._epsilon = e;
  47785. this.collisionFound = false;
  47786. };
  47787. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  47788. pa.subtractToRef(point, this._tempVector);
  47789. pb.subtractToRef(point, this._tempVector2);
  47790. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  47791. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47792. if (d < 0)
  47793. return false;
  47794. pc.subtractToRef(point, this._tempVector3);
  47795. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  47796. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47797. if (d < 0)
  47798. return false;
  47799. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  47800. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47801. return d >= 0;
  47802. };
  47803. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  47804. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  47805. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  47806. if (distance > this._velocityWorldLength + max + sphereRadius) {
  47807. return false;
  47808. }
  47809. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  47810. return false;
  47811. return true;
  47812. };
  47813. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  47814. var t0;
  47815. var embeddedInPlane = false;
  47816. //defensive programming, actually not needed.
  47817. if (!trianglePlaneArray) {
  47818. trianglePlaneArray = [];
  47819. }
  47820. if (!trianglePlaneArray[faceIndex]) {
  47821. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  47822. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  47823. }
  47824. var trianglePlane = trianglePlaneArray[faceIndex];
  47825. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  47826. return;
  47827. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  47828. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  47829. if (normalDotVelocity == 0) {
  47830. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  47831. return;
  47832. embeddedInPlane = true;
  47833. t0 = 0;
  47834. }
  47835. else {
  47836. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47837. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47838. if (t0 > t1) {
  47839. var temp = t1;
  47840. t1 = t0;
  47841. t0 = temp;
  47842. }
  47843. if (t0 > 1.0 || t1 < 0.0)
  47844. return;
  47845. if (t0 < 0)
  47846. t0 = 0;
  47847. if (t0 > 1.0)
  47848. t0 = 1.0;
  47849. }
  47850. this._collisionPoint.copyFromFloats(0, 0, 0);
  47851. var found = false;
  47852. var t = 1.0;
  47853. if (!embeddedInPlane) {
  47854. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  47855. this._velocity.scaleToRef(t0, this._tempVector);
  47856. this._planeIntersectionPoint.addInPlace(this._tempVector);
  47857. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  47858. found = true;
  47859. t = t0;
  47860. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  47861. }
  47862. }
  47863. if (!found) {
  47864. var velocitySquaredLength = this._velocity.lengthSquared();
  47865. var a = velocitySquaredLength;
  47866. this._basePoint.subtractToRef(p1, this._tempVector);
  47867. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47868. var c = this._tempVector.lengthSquared() - 1.0;
  47869. var lowestRoot = getLowestRoot(a, b, c, t);
  47870. if (lowestRoot.found) {
  47871. t = lowestRoot.root;
  47872. found = true;
  47873. this._collisionPoint.copyFrom(p1);
  47874. }
  47875. this._basePoint.subtractToRef(p2, this._tempVector);
  47876. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47877. c = this._tempVector.lengthSquared() - 1.0;
  47878. lowestRoot = getLowestRoot(a, b, c, t);
  47879. if (lowestRoot.found) {
  47880. t = lowestRoot.root;
  47881. found = true;
  47882. this._collisionPoint.copyFrom(p2);
  47883. }
  47884. this._basePoint.subtractToRef(p3, this._tempVector);
  47885. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47886. c = this._tempVector.lengthSquared() - 1.0;
  47887. lowestRoot = getLowestRoot(a, b, c, t);
  47888. if (lowestRoot.found) {
  47889. t = lowestRoot.root;
  47890. found = true;
  47891. this._collisionPoint.copyFrom(p3);
  47892. }
  47893. p2.subtractToRef(p1, this._edge);
  47894. p1.subtractToRef(this._basePoint, this._baseToVertex);
  47895. var edgeSquaredLength = this._edge.lengthSquared();
  47896. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47897. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47898. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47899. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47900. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47901. lowestRoot = getLowestRoot(a, b, c, t);
  47902. if (lowestRoot.found) {
  47903. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47904. if (f >= 0.0 && f <= 1.0) {
  47905. t = lowestRoot.root;
  47906. found = true;
  47907. this._edge.scaleInPlace(f);
  47908. p1.addToRef(this._edge, this._collisionPoint);
  47909. }
  47910. }
  47911. p3.subtractToRef(p2, this._edge);
  47912. p2.subtractToRef(this._basePoint, this._baseToVertex);
  47913. edgeSquaredLength = this._edge.lengthSquared();
  47914. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47915. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47916. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47917. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47918. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47919. lowestRoot = getLowestRoot(a, b, c, t);
  47920. if (lowestRoot.found) {
  47921. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47922. if (f >= 0.0 && f <= 1.0) {
  47923. t = lowestRoot.root;
  47924. found = true;
  47925. this._edge.scaleInPlace(f);
  47926. p2.addToRef(this._edge, this._collisionPoint);
  47927. }
  47928. }
  47929. p1.subtractToRef(p3, this._edge);
  47930. p3.subtractToRef(this._basePoint, this._baseToVertex);
  47931. edgeSquaredLength = this._edge.lengthSquared();
  47932. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47933. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47934. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47935. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47936. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47937. lowestRoot = getLowestRoot(a, b, c, t);
  47938. if (lowestRoot.found) {
  47939. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47940. if (f >= 0.0 && f <= 1.0) {
  47941. t = lowestRoot.root;
  47942. found = true;
  47943. this._edge.scaleInPlace(f);
  47944. p3.addToRef(this._edge, this._collisionPoint);
  47945. }
  47946. }
  47947. }
  47948. if (found) {
  47949. var distToCollision = t * this._velocity.length();
  47950. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  47951. if (!this.intersectionPoint) {
  47952. this.intersectionPoint = this._collisionPoint.clone();
  47953. }
  47954. else {
  47955. this.intersectionPoint.copyFrom(this._collisionPoint);
  47956. }
  47957. this._nearestDistance = distToCollision;
  47958. this.collisionFound = true;
  47959. }
  47960. }
  47961. };
  47962. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  47963. for (var i = indexStart; i < indexEnd; i += 3) {
  47964. var p1 = pts[indices[i] - decal];
  47965. var p2 = pts[indices[i + 1] - decal];
  47966. var p3 = pts[indices[i + 2] - decal];
  47967. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  47968. }
  47969. };
  47970. Collider.prototype._getResponse = function (pos, vel) {
  47971. pos.addToRef(vel, this._destinationPoint);
  47972. vel.scaleInPlace((this._nearestDistance / vel.length()));
  47973. this._basePoint.addToRef(vel, pos);
  47974. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  47975. this._slidePlaneNormal.normalize();
  47976. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  47977. pos.addInPlace(this._displacementVector);
  47978. this.intersectionPoint.addInPlace(this._displacementVector);
  47979. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  47980. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  47981. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  47982. };
  47983. return Collider;
  47984. }());
  47985. BABYLON.Collider = Collider;
  47986. })(BABYLON || (BABYLON = {}));
  47987. //# sourceMappingURL=babylon.collider.js.map
  47988. var BABYLON;
  47989. (function (BABYLON) {
  47990. //WebWorker code will be inserted to this variable.
  47991. BABYLON.CollisionWorker = "";
  47992. var WorkerTaskType;
  47993. (function (WorkerTaskType) {
  47994. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  47995. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  47996. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  47997. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  47998. var WorkerReplyType;
  47999. (function (WorkerReplyType) {
  48000. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  48001. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  48002. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  48003. var CollisionCoordinatorWorker = /** @class */ (function () {
  48004. function CollisionCoordinatorWorker() {
  48005. var _this = this;
  48006. this._scaledPosition = BABYLON.Vector3.Zero();
  48007. this._scaledVelocity = BABYLON.Vector3.Zero();
  48008. this.onMeshUpdated = function (transformNode) {
  48009. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  48010. };
  48011. this.onGeometryUpdated = function (geometry) {
  48012. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  48013. };
  48014. this._afterRender = function () {
  48015. if (!_this._init)
  48016. return;
  48017. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  48018. return;
  48019. }
  48020. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  48021. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  48022. if (_this._runningUpdated > 4) {
  48023. return;
  48024. }
  48025. ++_this._runningUpdated;
  48026. var payload = {
  48027. updatedMeshes: _this._addUpdateMeshesList,
  48028. updatedGeometries: _this._addUpdateGeometriesList,
  48029. removedGeometries: _this._toRemoveGeometryArray,
  48030. removedMeshes: _this._toRemoveMeshesArray
  48031. };
  48032. var message = {
  48033. payload: payload,
  48034. taskType: WorkerTaskType.UPDATE
  48035. };
  48036. var serializable = [];
  48037. for (var id in payload.updatedGeometries) {
  48038. if (payload.updatedGeometries.hasOwnProperty(id)) {
  48039. //prepare transferables
  48040. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  48041. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  48042. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  48043. }
  48044. }
  48045. _this._worker.postMessage(message, serializable);
  48046. _this._addUpdateMeshesList = {};
  48047. _this._addUpdateGeometriesList = {};
  48048. _this._toRemoveGeometryArray = [];
  48049. _this._toRemoveMeshesArray = [];
  48050. };
  48051. this._onMessageFromWorker = function (e) {
  48052. var returnData = e.data;
  48053. if (returnData.error != WorkerReplyType.SUCCESS) {
  48054. //TODO what errors can be returned from the worker?
  48055. BABYLON.Tools.Warn("error returned from worker!");
  48056. return;
  48057. }
  48058. switch (returnData.taskType) {
  48059. case WorkerTaskType.INIT:
  48060. _this._init = true;
  48061. //Update the worked with ALL of the scene's current state
  48062. _this._scene.meshes.forEach(function (mesh) {
  48063. _this.onMeshAdded(mesh);
  48064. });
  48065. _this._scene.getGeometries().forEach(function (geometry) {
  48066. _this.onGeometryAdded(geometry);
  48067. });
  48068. break;
  48069. case WorkerTaskType.UPDATE:
  48070. _this._runningUpdated--;
  48071. break;
  48072. case WorkerTaskType.COLLIDE:
  48073. var returnPayload = returnData.payload;
  48074. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  48075. return;
  48076. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  48077. if (callback) {
  48078. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  48079. if (mesh) {
  48080. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  48081. }
  48082. }
  48083. //cleanup
  48084. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  48085. break;
  48086. }
  48087. };
  48088. this._collisionsCallbackArray = [];
  48089. this._init = false;
  48090. this._runningUpdated = 0;
  48091. this._addUpdateMeshesList = {};
  48092. this._addUpdateGeometriesList = {};
  48093. this._toRemoveGeometryArray = [];
  48094. this._toRemoveMeshesArray = [];
  48095. }
  48096. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  48097. if (!this._init)
  48098. return;
  48099. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  48100. return;
  48101. position.divideToRef(collider._radius, this._scaledPosition);
  48102. displacement.divideToRef(collider._radius, this._scaledVelocity);
  48103. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  48104. var payload = {
  48105. collider: {
  48106. position: this._scaledPosition.asArray(),
  48107. velocity: this._scaledVelocity.asArray(),
  48108. radius: collider._radius.asArray()
  48109. },
  48110. collisionId: collisionIndex,
  48111. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  48112. maximumRetry: maximumRetry
  48113. };
  48114. var message = {
  48115. payload: payload,
  48116. taskType: WorkerTaskType.COLLIDE
  48117. };
  48118. this._worker.postMessage(message);
  48119. };
  48120. CollisionCoordinatorWorker.prototype.init = function (scene) {
  48121. this._scene = scene;
  48122. this._scene.registerAfterRender(this._afterRender);
  48123. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  48124. this._worker = new Worker(workerUrl);
  48125. this._worker.onmessage = this._onMessageFromWorker;
  48126. var message = {
  48127. payload: {},
  48128. taskType: WorkerTaskType.INIT
  48129. };
  48130. this._worker.postMessage(message);
  48131. };
  48132. CollisionCoordinatorWorker.prototype.destroy = function () {
  48133. this._scene.unregisterAfterRender(this._afterRender);
  48134. this._worker.terminate();
  48135. };
  48136. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  48137. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  48138. this.onMeshUpdated(mesh);
  48139. };
  48140. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  48141. this._toRemoveMeshesArray.push(mesh.uniqueId);
  48142. };
  48143. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  48144. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  48145. geometry.onGeometryUpdated = this.onGeometryUpdated;
  48146. this.onGeometryUpdated(geometry);
  48147. };
  48148. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  48149. this._toRemoveGeometryArray.push(geometry.id);
  48150. };
  48151. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  48152. var submeshes = [];
  48153. if (mesh.subMeshes) {
  48154. submeshes = mesh.subMeshes.map(function (sm, idx) {
  48155. var boundingInfo = sm.getBoundingInfo();
  48156. return {
  48157. position: idx,
  48158. verticesStart: sm.verticesStart,
  48159. verticesCount: sm.verticesCount,
  48160. indexStart: sm.indexStart,
  48161. indexCount: sm.indexCount,
  48162. hasMaterial: !!sm.getMaterial(),
  48163. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  48164. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  48165. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  48166. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  48167. };
  48168. });
  48169. }
  48170. var geometryId = null;
  48171. if (mesh instanceof BABYLON.Mesh) {
  48172. var geometry = mesh.geometry;
  48173. geometryId = geometry ? geometry.id : null;
  48174. }
  48175. else if (mesh instanceof BABYLON.InstancedMesh) {
  48176. var geometry = mesh.sourceMesh.geometry;
  48177. geometryId = geometry ? geometry.id : null;
  48178. }
  48179. var boundingInfo = mesh.getBoundingInfo();
  48180. return {
  48181. uniqueId: mesh.uniqueId,
  48182. id: mesh.id,
  48183. name: mesh.name,
  48184. geometryId: geometryId,
  48185. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  48186. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  48187. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  48188. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  48189. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  48190. subMeshes: submeshes,
  48191. checkCollisions: mesh.checkCollisions
  48192. };
  48193. };
  48194. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  48195. return {
  48196. id: geometry.id,
  48197. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  48198. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  48199. indices: new Uint32Array(geometry.getIndices() || []),
  48200. };
  48201. };
  48202. return CollisionCoordinatorWorker;
  48203. }());
  48204. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  48205. var CollisionCoordinatorLegacy = /** @class */ (function () {
  48206. function CollisionCoordinatorLegacy() {
  48207. this._scaledPosition = BABYLON.Vector3.Zero();
  48208. this._scaledVelocity = BABYLON.Vector3.Zero();
  48209. this._finalPosition = BABYLON.Vector3.Zero();
  48210. }
  48211. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  48212. position.divideToRef(collider._radius, this._scaledPosition);
  48213. displacement.divideToRef(collider._radius, this._scaledVelocity);
  48214. collider.collidedMesh = null;
  48215. collider._retry = 0;
  48216. collider._initialVelocity = this._scaledVelocity;
  48217. collider._initialPosition = this._scaledPosition;
  48218. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  48219. this._finalPosition.multiplyInPlace(collider._radius);
  48220. //run the callback
  48221. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  48222. };
  48223. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  48224. this._scene = scene;
  48225. };
  48226. CollisionCoordinatorLegacy.prototype.destroy = function () {
  48227. //Legacy need no destruction method.
  48228. };
  48229. //No update in legacy mode
  48230. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  48231. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  48232. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  48233. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  48234. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  48235. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  48236. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  48237. if (excludedMesh === void 0) { excludedMesh = null; }
  48238. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  48239. if (collider._retry >= maximumRetry) {
  48240. finalPosition.copyFrom(position);
  48241. return;
  48242. }
  48243. // Check if this is a mesh else camera or -1
  48244. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  48245. collider._initialize(position, velocity, closeDistance);
  48246. // Check all meshes
  48247. for (var index = 0; index < this._scene.meshes.length; index++) {
  48248. var mesh = this._scene.meshes[index];
  48249. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  48250. mesh._checkCollision(collider);
  48251. }
  48252. }
  48253. if (!collider.collisionFound) {
  48254. position.addToRef(velocity, finalPosition);
  48255. return;
  48256. }
  48257. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  48258. collider._getResponse(position, velocity);
  48259. }
  48260. if (velocity.length() <= closeDistance) {
  48261. finalPosition.copyFrom(position);
  48262. return;
  48263. }
  48264. collider._retry++;
  48265. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  48266. };
  48267. return CollisionCoordinatorLegacy;
  48268. }());
  48269. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  48270. })(BABYLON || (BABYLON = {}));
  48271. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  48272. var BABYLON;
  48273. (function (BABYLON) {
  48274. /**
  48275. * A particle represents one of the element emitted by a particle system.
  48276. * This is mainly define by its coordinates, direction, velocity and age.
  48277. */
  48278. var Particle = /** @class */ (function () {
  48279. /**
  48280. * Creates a new instance of @see Particle
  48281. * @param particleSystem the particle system the particle belongs to
  48282. */
  48283. function Particle(particleSystem) {
  48284. this.particleSystem = particleSystem;
  48285. /**
  48286. * The world position of the particle in the scene.
  48287. */
  48288. this.position = BABYLON.Vector3.Zero();
  48289. /**
  48290. * The world direction of the particle in the scene.
  48291. */
  48292. this.direction = BABYLON.Vector3.Zero();
  48293. /**
  48294. * The color of the particle.
  48295. */
  48296. this.color = new BABYLON.Color4(0, 0, 0, 0);
  48297. /**
  48298. * The color change of the particle per step.
  48299. */
  48300. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  48301. /**
  48302. * Defines how long will the life of the particle be.
  48303. */
  48304. this.lifeTime = 1.0;
  48305. /**
  48306. * The current age of the particle.
  48307. */
  48308. this.age = 0;
  48309. /**
  48310. * The current size of the particle.
  48311. */
  48312. this.size = 0;
  48313. /**
  48314. * The current angle of the particle.
  48315. */
  48316. this.angle = 0;
  48317. /**
  48318. * Defines how fast is the angle changing.
  48319. */
  48320. this.angularSpeed = 0;
  48321. /**
  48322. * Defines the cell index used by the particle to be rendered from a sprite.
  48323. */
  48324. this.cellIndex = 0;
  48325. this._currentFrameCounter = 0;
  48326. if (!this.particleSystem.isAnimationSheetEnabled) {
  48327. return;
  48328. }
  48329. this.cellIndex = this.particleSystem.startSpriteCellID;
  48330. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  48331. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  48332. }
  48333. else {
  48334. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  48335. }
  48336. }
  48337. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  48338. // (ageOffset / scaledUpdateSpeed) / available cells
  48339. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  48340. this._currentFrameCounter += scaledUpdateSpeed;
  48341. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  48342. this._currentFrameCounter = 0;
  48343. this.cellIndex++;
  48344. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48345. this.cellIndex = this.particleSystem.endSpriteCellID;
  48346. }
  48347. }
  48348. };
  48349. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  48350. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  48351. this.cellIndex++;
  48352. this._currentFrameCounter = 0;
  48353. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48354. if (this.particleSystem.spriteCellLoop) {
  48355. this.cellIndex = this.particleSystem.startSpriteCellID;
  48356. }
  48357. else {
  48358. this.cellIndex = this.particleSystem.endSpriteCellID;
  48359. }
  48360. }
  48361. }
  48362. else {
  48363. this._currentFrameCounter++;
  48364. }
  48365. };
  48366. /**
  48367. * Copy the properties of particle to another one.
  48368. * @param other the particle to copy the information to.
  48369. */
  48370. Particle.prototype.copyTo = function (other) {
  48371. other.position.copyFrom(this.position);
  48372. other.direction.copyFrom(this.direction);
  48373. other.color.copyFrom(this.color);
  48374. other.colorStep.copyFrom(this.colorStep);
  48375. other.lifeTime = this.lifeTime;
  48376. other.age = this.age;
  48377. other.size = this.size;
  48378. other.angle = this.angle;
  48379. other.angularSpeed = this.angularSpeed;
  48380. other.particleSystem = this.particleSystem;
  48381. other.cellIndex = this.cellIndex;
  48382. };
  48383. return Particle;
  48384. }());
  48385. BABYLON.Particle = Particle;
  48386. })(BABYLON || (BABYLON = {}));
  48387. //# sourceMappingURL=babylon.particle.js.map
  48388. var BABYLON;
  48389. (function (BABYLON) {
  48390. /**
  48391. * This represents a particle system in Babylon.
  48392. * 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.
  48393. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  48394. * @example https://doc.babylonjs.com/babylon101/particles
  48395. */
  48396. var ParticleSystem = /** @class */ (function () {
  48397. /**
  48398. * Instantiates a particle system.
  48399. * 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.
  48400. * @param name The name of the particle system
  48401. * @param capacity The max number of particles alive at the same time
  48402. * @param scene The scene the particle system belongs to
  48403. * @param customEffect a custom effect used to change the way particles are rendered by default
  48404. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  48405. * @param epsilon Offset used to render the particles
  48406. */
  48407. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  48408. if (customEffect === void 0) { customEffect = null; }
  48409. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  48410. if (epsilon === void 0) { epsilon = 0.01; }
  48411. var _this = this;
  48412. /**
  48413. * List of animations used by the particle system.
  48414. */
  48415. this.animations = [];
  48416. /**
  48417. * The rendering group used by the Particle system to chose when to render.
  48418. */
  48419. this.renderingGroupId = 0;
  48420. /**
  48421. * The emitter represents the Mesh or position we are attaching the particle system to.
  48422. */
  48423. this.emitter = null;
  48424. /**
  48425. * The density of particles, the rate of particle flow
  48426. */
  48427. this.emitRate = 10;
  48428. /**
  48429. * If you want to launch only a few particles at once, that can be done, as well.
  48430. */
  48431. this.manualEmitCount = -1;
  48432. /**
  48433. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  48434. */
  48435. this.updateSpeed = 0.01;
  48436. /**
  48437. * The amount of time the particle system is running (depends of the overall speed above).
  48438. */
  48439. this.targetStopDuration = 0;
  48440. /**
  48441. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  48442. */
  48443. this.disposeOnStop = false;
  48444. /**
  48445. * Minimum power of emitting particles.
  48446. */
  48447. this.minEmitPower = 1;
  48448. /**
  48449. * Maximum power of emitting particles.
  48450. */
  48451. this.maxEmitPower = 1;
  48452. /**
  48453. * Minimum life time of emitting particles.
  48454. */
  48455. this.minLifeTime = 1;
  48456. /**
  48457. * Maximum life time of emitting particles.
  48458. */
  48459. this.maxLifeTime = 1;
  48460. /**
  48461. * Minimum Size of emitting particles.
  48462. */
  48463. this.minSize = 1;
  48464. /**
  48465. * Maximum Size of emitting particles.
  48466. */
  48467. this.maxSize = 1;
  48468. /**
  48469. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  48470. */
  48471. this.minAngularSpeed = 0;
  48472. /**
  48473. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  48474. */
  48475. this.maxAngularSpeed = 0;
  48476. /**
  48477. * The layer mask we are rendering the particles through.
  48478. */
  48479. this.layerMask = 0x0FFFFFFF;
  48480. /**
  48481. * This can help using your own shader to render the particle system.
  48482. * The according effect will be created
  48483. */
  48484. this.customShader = null;
  48485. /**
  48486. * By default particle system starts as soon as they are created. This prevents the
  48487. * automatic start to happen and let you decide when to start emitting particles.
  48488. */
  48489. this.preventAutoStart = false;
  48490. /**
  48491. * Callback triggered when the particle animation is ending.
  48492. */
  48493. this.onAnimationEnd = null;
  48494. /**
  48495. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  48496. */
  48497. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  48498. /**
  48499. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  48500. * to override the particles.
  48501. */
  48502. this.forceDepthWrite = false;
  48503. /**
  48504. * You can use gravity if you want to give an orientation to your particles.
  48505. */
  48506. this.gravity = BABYLON.Vector3.Zero();
  48507. /**
  48508. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48509. */
  48510. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  48511. /**
  48512. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48513. */
  48514. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  48515. /**
  48516. * 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.
  48517. */
  48518. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  48519. /**
  48520. * 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.
  48521. */
  48522. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48523. /**
  48524. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48525. */
  48526. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48527. /**
  48528. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48529. */
  48530. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48531. /**
  48532. * Color the particle will have at the end of its lifetime.
  48533. */
  48534. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  48535. /**
  48536. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  48537. */
  48538. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48539. /**
  48540. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  48541. */
  48542. this.spriteCellLoop = true;
  48543. /**
  48544. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  48545. */
  48546. this.spriteCellChangeSpeed = 0;
  48547. /**
  48548. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  48549. */
  48550. this.startSpriteCellID = 0;
  48551. /**
  48552. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  48553. */
  48554. this.endSpriteCellID = 0;
  48555. /**
  48556. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  48557. */
  48558. this.spriteCellWidth = 0;
  48559. /**
  48560. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  48561. */
  48562. this.spriteCellHeight = 0;
  48563. /**
  48564. * An event triggered when the system is disposed.
  48565. */
  48566. this.onDisposeObservable = new BABYLON.Observable();
  48567. this._particles = new Array();
  48568. this._stockParticles = new Array();
  48569. this._newPartsExcess = 0;
  48570. this._vertexBuffers = {};
  48571. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  48572. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  48573. this._scaledDirection = BABYLON.Vector3.Zero();
  48574. this._scaledGravity = BABYLON.Vector3.Zero();
  48575. this._currentRenderId = -1;
  48576. this._started = false;
  48577. this._stopped = false;
  48578. this._actualFrame = 0;
  48579. this._vertexBufferSize = 11;
  48580. this._appendParticleVertexes = null;
  48581. this.id = name;
  48582. this.name = name;
  48583. this._capacity = capacity;
  48584. this._epsilon = epsilon;
  48585. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  48586. if (isAnimationSheetEnabled) {
  48587. this._vertexBufferSize = 12;
  48588. }
  48589. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48590. this._customEffect = customEffect;
  48591. scene.particleSystems.push(this);
  48592. this._createIndexBuffer();
  48593. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  48594. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  48595. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  48596. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  48597. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  48598. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  48599. if (this._isAnimationSheetEnabled) {
  48600. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  48601. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  48602. }
  48603. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48604. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48605. this._vertexBuffers["options"] = options;
  48606. // Default behaviors
  48607. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  48608. this.updateFunction = function (particles) {
  48609. for (var index = 0; index < particles.length; index++) {
  48610. var particle = particles[index];
  48611. particle.age += _this._scaledUpdateSpeed;
  48612. if (particle.age >= particle.lifeTime) {
  48613. _this.recycleParticle(particle);
  48614. index--;
  48615. continue;
  48616. }
  48617. else {
  48618. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  48619. particle.color.addInPlace(_this._scaledColorStep);
  48620. if (particle.color.a < 0)
  48621. particle.color.a = 0;
  48622. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  48623. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  48624. particle.position.addInPlace(_this._scaledDirection);
  48625. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  48626. particle.direction.addInPlace(_this._scaledGravity);
  48627. if (_this._isAnimationSheetEnabled) {
  48628. particle.updateCellIndex(_this._scaledUpdateSpeed);
  48629. }
  48630. }
  48631. }
  48632. };
  48633. }
  48634. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  48635. /**
  48636. * Sets a callback that will be triggered when the system is disposed.
  48637. */
  48638. set: function (callback) {
  48639. if (this._onDisposeObserver) {
  48640. this.onDisposeObservable.remove(this._onDisposeObserver);
  48641. }
  48642. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48643. },
  48644. enumerable: true,
  48645. configurable: true
  48646. });
  48647. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  48648. /**
  48649. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  48650. */
  48651. get: function () {
  48652. return this._isAnimationSheetEnabled;
  48653. },
  48654. enumerable: true,
  48655. configurable: true
  48656. });
  48657. ParticleSystem.prototype._createIndexBuffer = function () {
  48658. var indices = [];
  48659. var index = 0;
  48660. for (var count = 0; count < this._capacity; count++) {
  48661. indices.push(index);
  48662. indices.push(index + 1);
  48663. indices.push(index + 2);
  48664. indices.push(index);
  48665. indices.push(index + 2);
  48666. indices.push(index + 3);
  48667. index += 4;
  48668. }
  48669. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  48670. };
  48671. /**
  48672. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  48673. * Its lifetime will start back at 0.
  48674. * @param particle The particle to recycle
  48675. */
  48676. ParticleSystem.prototype.recycleParticle = function (particle) {
  48677. var lastParticle = this._particles.pop();
  48678. if (lastParticle !== particle) {
  48679. lastParticle.copyTo(particle);
  48680. this._stockParticles.push(lastParticle);
  48681. }
  48682. };
  48683. /**
  48684. * Gets the maximum number of particles active at the same time.
  48685. * @returns The max number of active particles.
  48686. */
  48687. ParticleSystem.prototype.getCapacity = function () {
  48688. return this._capacity;
  48689. };
  48690. /**
  48691. * Gets Wether there are still active particles in the system.
  48692. * @returns True if it is alive, otherwise false.
  48693. */
  48694. ParticleSystem.prototype.isAlive = function () {
  48695. return this._alive;
  48696. };
  48697. /**
  48698. * Gets Wether the system has been started.
  48699. * @returns True if it has been started, otherwise false.
  48700. */
  48701. ParticleSystem.prototype.isStarted = function () {
  48702. return this._started;
  48703. };
  48704. /**
  48705. * Starts the particle system and begins to emit.
  48706. */
  48707. ParticleSystem.prototype.start = function () {
  48708. this._started = true;
  48709. this._stopped = false;
  48710. this._actualFrame = 0;
  48711. };
  48712. /**
  48713. * Stops the particle system.
  48714. */
  48715. ParticleSystem.prototype.stop = function () {
  48716. this._stopped = true;
  48717. };
  48718. /**
  48719. * @ignore (for internal use only)
  48720. */
  48721. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  48722. var offset = index * this._vertexBufferSize;
  48723. this._vertexData[offset] = particle.position.x;
  48724. this._vertexData[offset + 1] = particle.position.y;
  48725. this._vertexData[offset + 2] = particle.position.z;
  48726. this._vertexData[offset + 3] = particle.color.r;
  48727. this._vertexData[offset + 4] = particle.color.g;
  48728. this._vertexData[offset + 5] = particle.color.b;
  48729. this._vertexData[offset + 6] = particle.color.a;
  48730. this._vertexData[offset + 7] = particle.angle;
  48731. this._vertexData[offset + 8] = particle.size;
  48732. this._vertexData[offset + 9] = offsetX;
  48733. this._vertexData[offset + 10] = offsetY;
  48734. };
  48735. /**
  48736. * @ignore (for internal use only)
  48737. */
  48738. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  48739. if (offsetX === 0)
  48740. offsetX = this._epsilon;
  48741. else if (offsetX === 1)
  48742. offsetX = 1 - this._epsilon;
  48743. if (offsetY === 0)
  48744. offsetY = this._epsilon;
  48745. else if (offsetY === 1)
  48746. offsetY = 1 - this._epsilon;
  48747. var offset = index * this._vertexBufferSize;
  48748. this._vertexData[offset] = particle.position.x;
  48749. this._vertexData[offset + 1] = particle.position.y;
  48750. this._vertexData[offset + 2] = particle.position.z;
  48751. this._vertexData[offset + 3] = particle.color.r;
  48752. this._vertexData[offset + 4] = particle.color.g;
  48753. this._vertexData[offset + 5] = particle.color.b;
  48754. this._vertexData[offset + 6] = particle.color.a;
  48755. this._vertexData[offset + 7] = particle.angle;
  48756. this._vertexData[offset + 8] = particle.size;
  48757. this._vertexData[offset + 9] = offsetX;
  48758. this._vertexData[offset + 10] = offsetY;
  48759. this._vertexData[offset + 11] = particle.cellIndex;
  48760. };
  48761. ParticleSystem.prototype._update = function (newParticles) {
  48762. // Update current
  48763. this._alive = this._particles.length > 0;
  48764. this.updateFunction(this._particles);
  48765. // Add new ones
  48766. var worldMatrix;
  48767. if (this.emitter.position) {
  48768. var emitterMesh = this.emitter;
  48769. worldMatrix = emitterMesh.getWorldMatrix();
  48770. }
  48771. else {
  48772. var emitterPosition = this.emitter;
  48773. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  48774. }
  48775. var particle;
  48776. for (var index = 0; index < newParticles; index++) {
  48777. if (this._particles.length === this._capacity) {
  48778. break;
  48779. }
  48780. if (this._stockParticles.length !== 0) {
  48781. particle = this._stockParticles.pop();
  48782. particle.age = 0;
  48783. particle.cellIndex = this.startSpriteCellID;
  48784. }
  48785. else {
  48786. particle = new BABYLON.Particle(this);
  48787. }
  48788. this._particles.push(particle);
  48789. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  48790. if (this.startPositionFunction) {
  48791. this.startPositionFunction(worldMatrix, particle.position, particle);
  48792. }
  48793. else {
  48794. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  48795. }
  48796. if (this.startDirectionFunction) {
  48797. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48798. }
  48799. else {
  48800. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48801. }
  48802. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  48803. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  48804. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  48805. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  48806. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  48807. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  48808. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  48809. }
  48810. };
  48811. ParticleSystem.prototype._getEffect = function () {
  48812. if (this._customEffect) {
  48813. return this._customEffect;
  48814. }
  48815. ;
  48816. var defines = [];
  48817. if (this._scene.clipPlane) {
  48818. defines.push("#define CLIPPLANE");
  48819. }
  48820. if (this._isAnimationSheetEnabled) {
  48821. defines.push("#define ANIMATESHEET");
  48822. }
  48823. // Effect
  48824. var join = defines.join("\n");
  48825. if (this._cachedDefines !== join) {
  48826. this._cachedDefines = join;
  48827. var attributesNamesOrOptions;
  48828. var effectCreationOption;
  48829. if (this._isAnimationSheetEnabled) {
  48830. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  48831. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  48832. }
  48833. else {
  48834. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  48835. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  48836. }
  48837. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  48838. }
  48839. return this._effect;
  48840. };
  48841. /**
  48842. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  48843. */
  48844. ParticleSystem.prototype.animate = function () {
  48845. if (!this._started)
  48846. return;
  48847. var effect = this._getEffect();
  48848. // Check
  48849. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  48850. return;
  48851. if (this._currentRenderId === this._scene.getRenderId()) {
  48852. return;
  48853. }
  48854. this._currentRenderId = this._scene.getRenderId();
  48855. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  48856. // determine the number of particles we need to create
  48857. var newParticles;
  48858. if (this.manualEmitCount > -1) {
  48859. newParticles = this.manualEmitCount;
  48860. this._newPartsExcess = 0;
  48861. this.manualEmitCount = 0;
  48862. }
  48863. else {
  48864. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  48865. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  48866. }
  48867. if (this._newPartsExcess > 1.0) {
  48868. newParticles += this._newPartsExcess >> 0;
  48869. this._newPartsExcess -= this._newPartsExcess >> 0;
  48870. }
  48871. this._alive = false;
  48872. if (!this._stopped) {
  48873. this._actualFrame += this._scaledUpdateSpeed;
  48874. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  48875. this.stop();
  48876. }
  48877. else {
  48878. newParticles = 0;
  48879. }
  48880. this._update(newParticles);
  48881. // Stopped?
  48882. if (this._stopped) {
  48883. if (!this._alive) {
  48884. this._started = false;
  48885. if (this.onAnimationEnd) {
  48886. this.onAnimationEnd();
  48887. }
  48888. if (this.disposeOnStop) {
  48889. this._scene._toBeDisposed.push(this);
  48890. }
  48891. }
  48892. }
  48893. // Animation sheet
  48894. if (this._isAnimationSheetEnabled) {
  48895. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  48896. }
  48897. else {
  48898. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  48899. }
  48900. // Update VBO
  48901. var offset = 0;
  48902. for (var index = 0; index < this._particles.length; index++) {
  48903. var particle = this._particles[index];
  48904. this._appendParticleVertexes(offset, particle);
  48905. offset += 4;
  48906. }
  48907. if (this._vertexBuffer) {
  48908. this._vertexBuffer.update(this._vertexData);
  48909. }
  48910. };
  48911. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  48912. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  48913. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  48914. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  48915. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  48916. };
  48917. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  48918. this._appendParticleVertex(offset++, particle, 0, 0);
  48919. this._appendParticleVertex(offset++, particle, 1, 0);
  48920. this._appendParticleVertex(offset++, particle, 1, 1);
  48921. this._appendParticleVertex(offset++, particle, 0, 1);
  48922. };
  48923. /**
  48924. * Rebuilds the particle system.
  48925. */
  48926. ParticleSystem.prototype.rebuild = function () {
  48927. this._createIndexBuffer();
  48928. if (this._vertexBuffer) {
  48929. this._vertexBuffer._rebuild();
  48930. }
  48931. };
  48932. /**
  48933. * Renders the particle system in its current state.
  48934. * @returns the current number of particles.
  48935. */
  48936. ParticleSystem.prototype.render = function () {
  48937. var effect = this._getEffect();
  48938. // Check
  48939. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  48940. return 0;
  48941. var engine = this._scene.getEngine();
  48942. // Render
  48943. engine.enableEffect(effect);
  48944. engine.setState(false);
  48945. var viewMatrix = this._scene.getViewMatrix();
  48946. effect.setTexture("diffuseSampler", this.particleTexture);
  48947. effect.setMatrix("view", viewMatrix);
  48948. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48949. if (this._isAnimationSheetEnabled) {
  48950. var baseSize = this.particleTexture.getBaseSize();
  48951. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  48952. }
  48953. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  48954. if (this._scene.clipPlane) {
  48955. var clipPlane = this._scene.clipPlane;
  48956. var invView = viewMatrix.clone();
  48957. invView.invert();
  48958. effect.setMatrix("invView", invView);
  48959. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  48960. }
  48961. // VBOs
  48962. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48963. // Draw order
  48964. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  48965. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  48966. }
  48967. else {
  48968. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48969. }
  48970. if (this.forceDepthWrite) {
  48971. engine.setDepthWrite(true);
  48972. }
  48973. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  48974. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48975. return this._particles.length;
  48976. };
  48977. /**
  48978. * Disposes the particle system and free the associated resources.
  48979. */
  48980. ParticleSystem.prototype.dispose = function () {
  48981. if (this._vertexBuffer) {
  48982. this._vertexBuffer.dispose();
  48983. this._vertexBuffer = null;
  48984. }
  48985. if (this._indexBuffer) {
  48986. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48987. this._indexBuffer = null;
  48988. }
  48989. if (this.particleTexture) {
  48990. this.particleTexture.dispose();
  48991. this.particleTexture = null;
  48992. }
  48993. // Remove from scene
  48994. var index = this._scene.particleSystems.indexOf(this);
  48995. if (index > -1) {
  48996. this._scene.particleSystems.splice(index, 1);
  48997. }
  48998. // Callback
  48999. this.onDisposeObservable.notifyObservers(this);
  49000. this.onDisposeObservable.clear();
  49001. };
  49002. /**
  49003. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  49004. * @param radius The radius of the sphere to emit from
  49005. * @returns the emitter
  49006. */
  49007. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  49008. if (radius === void 0) { radius = 1; }
  49009. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  49010. this.particleEmitterType = particleEmitter;
  49011. return particleEmitter;
  49012. };
  49013. /**
  49014. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  49015. * @param radius The radius of the sphere to emit from
  49016. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  49017. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  49018. * @returns the emitter
  49019. */
  49020. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  49021. if (radius === void 0) { radius = 1; }
  49022. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  49023. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  49024. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  49025. this.particleEmitterType = particleEmitter;
  49026. return particleEmitter;
  49027. };
  49028. /**
  49029. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  49030. * @param radius The radius of the cone to emit from
  49031. * @param angle The base angle of the cone
  49032. * @returns the emitter
  49033. */
  49034. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  49035. if (radius === void 0) { radius = 1; }
  49036. if (angle === void 0) { angle = Math.PI / 4; }
  49037. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  49038. this.particleEmitterType = particleEmitter;
  49039. return particleEmitter;
  49040. };
  49041. // 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.
  49042. /**
  49043. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  49044. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  49045. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  49046. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  49047. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  49048. * @returns the emitter
  49049. */
  49050. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  49051. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  49052. this.direction1 = direction1;
  49053. this.direction2 = direction2;
  49054. this.minEmitBox = minEmitBox;
  49055. this.maxEmitBox = maxEmitBox;
  49056. this.particleEmitterType = particleEmitter;
  49057. return particleEmitter;
  49058. };
  49059. /**
  49060. * Clones the particle system.
  49061. * @param name The name of the cloned object
  49062. * @param newEmitter The new emitter to use
  49063. * @returns the cloned particle system
  49064. */
  49065. ParticleSystem.prototype.clone = function (name, newEmitter) {
  49066. var custom = null;
  49067. var program = null;
  49068. if (this.customShader != null) {
  49069. program = this.customShader;
  49070. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  49071. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  49072. }
  49073. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  49074. result.customShader = program;
  49075. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  49076. if (newEmitter === undefined) {
  49077. newEmitter = this.emitter;
  49078. }
  49079. result.emitter = newEmitter;
  49080. if (this.particleTexture) {
  49081. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  49082. }
  49083. if (!this.preventAutoStart) {
  49084. result.start();
  49085. }
  49086. return result;
  49087. };
  49088. /**
  49089. * Serializes the particle system to a JSON object.
  49090. * @returns the JSON object
  49091. */
  49092. ParticleSystem.prototype.serialize = function () {
  49093. var serializationObject = {};
  49094. serializationObject.name = this.name;
  49095. serializationObject.id = this.id;
  49096. // Emitter
  49097. if (this.emitter.position) {
  49098. var emitterMesh = this.emitter;
  49099. serializationObject.emitterId = emitterMesh.id;
  49100. }
  49101. else {
  49102. var emitterPosition = this.emitter;
  49103. serializationObject.emitter = emitterPosition.asArray();
  49104. }
  49105. serializationObject.capacity = this.getCapacity();
  49106. if (this.particleTexture) {
  49107. serializationObject.textureName = this.particleTexture.name;
  49108. }
  49109. // Animations
  49110. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  49111. // Particle system
  49112. serializationObject.minAngularSpeed = this.minAngularSpeed;
  49113. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  49114. serializationObject.minSize = this.minSize;
  49115. serializationObject.maxSize = this.maxSize;
  49116. serializationObject.minEmitPower = this.minEmitPower;
  49117. serializationObject.maxEmitPower = this.maxEmitPower;
  49118. serializationObject.minLifeTime = this.minLifeTime;
  49119. serializationObject.maxLifeTime = this.maxLifeTime;
  49120. serializationObject.emitRate = this.emitRate;
  49121. serializationObject.minEmitBox = this.minEmitBox.asArray();
  49122. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  49123. serializationObject.gravity = this.gravity.asArray();
  49124. serializationObject.direction1 = this.direction1.asArray();
  49125. serializationObject.direction2 = this.direction2.asArray();
  49126. serializationObject.color1 = this.color1.asArray();
  49127. serializationObject.color2 = this.color2.asArray();
  49128. serializationObject.colorDead = this.colorDead.asArray();
  49129. serializationObject.updateSpeed = this.updateSpeed;
  49130. serializationObject.targetStopDuration = this.targetStopDuration;
  49131. serializationObject.textureMask = this.textureMask.asArray();
  49132. serializationObject.blendMode = this.blendMode;
  49133. serializationObject.customShader = this.customShader;
  49134. serializationObject.preventAutoStart = this.preventAutoStart;
  49135. serializationObject.startSpriteCellID = this.startSpriteCellID;
  49136. serializationObject.endSpriteCellID = this.endSpriteCellID;
  49137. serializationObject.spriteCellLoop = this.spriteCellLoop;
  49138. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  49139. serializationObject.spriteCellWidth = this.spriteCellWidth;
  49140. serializationObject.spriteCellHeight = this.spriteCellHeight;
  49141. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  49142. return serializationObject;
  49143. };
  49144. /**
  49145. * Parses a JSON object to create a particle system.
  49146. * @param parsedParticleSystem The JSON object to parse
  49147. * @param scene The scene to create the particle system in
  49148. * @param rootUrl The root url to use to load external dependencies like texture
  49149. * @returns the Parsed particle system
  49150. */
  49151. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  49152. var name = parsedParticleSystem.name;
  49153. var custom = null;
  49154. var program = null;
  49155. if (parsedParticleSystem.customShader) {
  49156. program = parsedParticleSystem.customShader;
  49157. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  49158. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  49159. }
  49160. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  49161. particleSystem.customShader = program;
  49162. if (parsedParticleSystem.id) {
  49163. particleSystem.id = parsedParticleSystem.id;
  49164. }
  49165. // Auto start
  49166. if (parsedParticleSystem.preventAutoStart) {
  49167. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  49168. }
  49169. // Texture
  49170. if (parsedParticleSystem.textureName) {
  49171. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  49172. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  49173. }
  49174. // Emitter
  49175. if (parsedParticleSystem.emitterId) {
  49176. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  49177. }
  49178. else {
  49179. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  49180. }
  49181. // Animations
  49182. if (parsedParticleSystem.animations) {
  49183. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  49184. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  49185. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49186. }
  49187. }
  49188. if (parsedParticleSystem.autoAnimate) {
  49189. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  49190. }
  49191. // Particle system
  49192. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  49193. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  49194. particleSystem.minSize = parsedParticleSystem.minSize;
  49195. particleSystem.maxSize = parsedParticleSystem.maxSize;
  49196. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  49197. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  49198. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  49199. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  49200. particleSystem.emitRate = parsedParticleSystem.emitRate;
  49201. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  49202. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  49203. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  49204. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  49205. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  49206. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  49207. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  49208. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  49209. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  49210. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  49211. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  49212. particleSystem.blendMode = parsedParticleSystem.blendMode;
  49213. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  49214. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  49215. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  49216. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  49217. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  49218. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  49219. if (!particleSystem.preventAutoStart) {
  49220. particleSystem.start();
  49221. }
  49222. return particleSystem;
  49223. };
  49224. /**
  49225. * Source color is added to the destination color without alpha affecting the result.
  49226. */
  49227. ParticleSystem.BLENDMODE_ONEONE = 0;
  49228. /**
  49229. * Blend current color and particle color using particle’s alpha.
  49230. */
  49231. ParticleSystem.BLENDMODE_STANDARD = 1;
  49232. return ParticleSystem;
  49233. }());
  49234. BABYLON.ParticleSystem = ParticleSystem;
  49235. })(BABYLON || (BABYLON = {}));
  49236. //# sourceMappingURL=babylon.particleSystem.js.map
  49237. var BABYLON;
  49238. (function (BABYLON) {
  49239. /**
  49240. * Particle emitter emitting particles from the inside of a box.
  49241. * It emits the particles randomly between 2 given directions.
  49242. */
  49243. var BoxParticleEmitter = /** @class */ (function () {
  49244. // to be updated like the rest of emitters when breaking changes.
  49245. // all property should be come public variables and passed through constructor.
  49246. /**
  49247. * Creates a new instance of @see BoxParticleEmitter
  49248. * @param _particleSystem the particle system associated with the emitter
  49249. */
  49250. function BoxParticleEmitter(_particleSystem) {
  49251. this._particleSystem = _particleSystem;
  49252. }
  49253. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  49254. /**
  49255. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49256. */
  49257. get: function () {
  49258. return this._particleSystem.direction1;
  49259. },
  49260. /**
  49261. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49262. */
  49263. set: function (value) {
  49264. this._particleSystem.direction1 = value;
  49265. },
  49266. enumerable: true,
  49267. configurable: true
  49268. });
  49269. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  49270. /**
  49271. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49272. */
  49273. get: function () {
  49274. return this._particleSystem.direction2;
  49275. },
  49276. /**
  49277. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49278. */
  49279. set: function (value) {
  49280. this._particleSystem.direction2 = value;
  49281. },
  49282. enumerable: true,
  49283. configurable: true
  49284. });
  49285. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  49286. /**
  49287. * 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.
  49288. */
  49289. get: function () {
  49290. return this._particleSystem.minEmitBox;
  49291. },
  49292. /**
  49293. * 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.
  49294. */
  49295. set: function (value) {
  49296. this._particleSystem.minEmitBox = value;
  49297. },
  49298. enumerable: true,
  49299. configurable: true
  49300. });
  49301. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  49302. /**
  49303. * 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.
  49304. */
  49305. get: function () {
  49306. return this._particleSystem.maxEmitBox;
  49307. },
  49308. /**
  49309. * 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.
  49310. */
  49311. set: function (value) {
  49312. this._particleSystem.maxEmitBox = value;
  49313. },
  49314. enumerable: true,
  49315. configurable: true
  49316. });
  49317. /**
  49318. * Called by the particle System when the direction is computed for the created particle.
  49319. * @param emitPower is the power of the particle (speed)
  49320. * @param worldMatrix is the world matrix of the particle system
  49321. * @param directionToUpdate is the direction vector to update with the result
  49322. * @param particle is the particle we are computed the direction for
  49323. */
  49324. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49325. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49326. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49327. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49328. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49329. };
  49330. /**
  49331. * Called by the particle System when the position is computed for the created particle.
  49332. * @param worldMatrix is the world matrix of the particle system
  49333. * @param positionToUpdate is the position vector to update with the result
  49334. * @param particle is the particle we are computed the position for
  49335. */
  49336. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49337. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  49338. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  49339. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  49340. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49341. };
  49342. /**
  49343. * Clones the current emitter and returns a copy of it
  49344. * @returns the new emitter
  49345. */
  49346. BoxParticleEmitter.prototype.clone = function () {
  49347. var newOne = new BoxParticleEmitter(this._particleSystem);
  49348. BABYLON.Tools.DeepCopy(this, newOne);
  49349. return newOne;
  49350. };
  49351. return BoxParticleEmitter;
  49352. }());
  49353. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  49354. })(BABYLON || (BABYLON = {}));
  49355. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  49356. var BABYLON;
  49357. (function (BABYLON) {
  49358. /**
  49359. * Particle emitter emitting particles from the inside of a cone.
  49360. * It emits the particles alongside the cone volume from the base to the particle.
  49361. * The emission direction might be randomized.
  49362. */
  49363. var ConeParticleEmitter = /** @class */ (function () {
  49364. /**
  49365. * Creates a new instance of @see ConeParticleEmitter
  49366. * @param radius the radius of the emission cone
  49367. * @param angles the cone base angle
  49368. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49369. */
  49370. function ConeParticleEmitter(radius,
  49371. /**
  49372. * The radius of the emission cone.
  49373. */
  49374. angle,
  49375. /**
  49376. * The cone base angle.
  49377. */
  49378. directionRandomizer) {
  49379. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49380. this.angle = angle;
  49381. this.directionRandomizer = directionRandomizer;
  49382. this.radius = radius;
  49383. }
  49384. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  49385. /**
  49386. * Gets the radius of the emission cone.
  49387. */
  49388. get: function () {
  49389. return this._radius;
  49390. },
  49391. /**
  49392. * Sets the radius of the emission cone.
  49393. */
  49394. set: function (value) {
  49395. this._radius = value;
  49396. if (this.angle !== 0) {
  49397. this._height = value / Math.tan(this.angle / 2);
  49398. }
  49399. else {
  49400. this._height = 1;
  49401. }
  49402. },
  49403. enumerable: true,
  49404. configurable: true
  49405. });
  49406. /**
  49407. * Called by the particle System when the direction is computed for the created particle.
  49408. * @param emitPower is the power of the particle (speed)
  49409. * @param worldMatrix is the world matrix of the particle system
  49410. * @param directionToUpdate is the direction vector to update with the result
  49411. * @param particle is the particle we are computed the direction for
  49412. */
  49413. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49414. if (this.angle === 0) {
  49415. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  49416. }
  49417. else {
  49418. // measure the direction Vector from the emitter to the particle.
  49419. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49420. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49421. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49422. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49423. direction.x += randX;
  49424. direction.y += randY;
  49425. direction.z += randZ;
  49426. direction.normalize();
  49427. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49428. }
  49429. };
  49430. /**
  49431. * Called by the particle System when the position is computed for the created particle.
  49432. * @param worldMatrix is the world matrix of the particle system
  49433. * @param positionToUpdate is the position vector to update with the result
  49434. * @param particle is the particle we are computed the position for
  49435. */
  49436. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49437. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  49438. var h = BABYLON.Scalar.RandomRange(0, 1);
  49439. // Better distribution in a cone at normal angles.
  49440. h = 1 - h * h;
  49441. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  49442. radius = radius * h / this._height;
  49443. var randX = radius * Math.sin(s);
  49444. var randZ = radius * Math.cos(s);
  49445. var randY = h;
  49446. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49447. };
  49448. /**
  49449. * Clones the current emitter and returns a copy of it
  49450. * @returns the new emitter
  49451. */
  49452. ConeParticleEmitter.prototype.clone = function () {
  49453. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  49454. BABYLON.Tools.DeepCopy(this, newOne);
  49455. return newOne;
  49456. };
  49457. return ConeParticleEmitter;
  49458. }());
  49459. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  49460. })(BABYLON || (BABYLON = {}));
  49461. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  49462. var BABYLON;
  49463. (function (BABYLON) {
  49464. /**
  49465. * Particle emitter emitting particles from the inside of a sphere.
  49466. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  49467. */
  49468. var SphereParticleEmitter = /** @class */ (function () {
  49469. /**
  49470. * Creates a new instance of @see SphereParticleEmitter
  49471. * @param radius the radius of the emission sphere
  49472. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49473. */
  49474. function SphereParticleEmitter(
  49475. /**
  49476. * The radius of the emission sphere.
  49477. */
  49478. radius,
  49479. /**
  49480. * How much to randomize the particle direction [0-1].
  49481. */
  49482. directionRandomizer) {
  49483. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49484. this.radius = radius;
  49485. this.directionRandomizer = directionRandomizer;
  49486. }
  49487. /**
  49488. * Called by the particle System when the direction is computed for the created particle.
  49489. * @param emitPower is the power of the particle (speed)
  49490. * @param worldMatrix is the world matrix of the particle system
  49491. * @param directionToUpdate is the direction vector to update with the result
  49492. * @param particle is the particle we are computed the direction for
  49493. */
  49494. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49495. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49496. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49497. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49498. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49499. direction.x += randX;
  49500. direction.y += randY;
  49501. direction.z += randZ;
  49502. direction.normalize();
  49503. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49504. };
  49505. /**
  49506. * Called by the particle System when the position is computed for the created particle.
  49507. * @param worldMatrix is the world matrix of the particle system
  49508. * @param positionToUpdate is the position vector to update with the result
  49509. * @param particle is the particle we are computed the position for
  49510. */
  49511. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49512. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  49513. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  49514. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  49515. var randY = this.radius * Math.cos(theta);
  49516. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  49517. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49518. };
  49519. /**
  49520. * Clones the current emitter and returns a copy of it
  49521. * @returns the new emitter
  49522. */
  49523. SphereParticleEmitter.prototype.clone = function () {
  49524. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  49525. BABYLON.Tools.DeepCopy(this, newOne);
  49526. return newOne;
  49527. };
  49528. return SphereParticleEmitter;
  49529. }());
  49530. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  49531. /**
  49532. * Particle emitter emitting particles from the inside of a sphere.
  49533. * It emits the particles randomly between two vectors.
  49534. */
  49535. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  49536. __extends(SphereDirectedParticleEmitter, _super);
  49537. /**
  49538. * Creates a new instance of @see SphereDirectedParticleEmitter
  49539. * @param radius the radius of the emission sphere
  49540. * @param direction1 the min limit of the emission direction
  49541. * @param direction2 the max limit of the emission direction
  49542. */
  49543. function SphereDirectedParticleEmitter(radius,
  49544. /**
  49545. * The min limit of the emission direction.
  49546. */
  49547. direction1,
  49548. /**
  49549. * The max limit of the emission direction.
  49550. */
  49551. direction2) {
  49552. var _this = _super.call(this, radius) || this;
  49553. _this.direction1 = direction1;
  49554. _this.direction2 = direction2;
  49555. return _this;
  49556. }
  49557. /**
  49558. * Called by the particle System when the direction is computed for the created particle.
  49559. * @param emitPower is the power of the particle (speed)
  49560. * @param worldMatrix is the world matrix of the particle system
  49561. * @param directionToUpdate is the direction vector to update with the result
  49562. * @param particle is the particle we are computed the direction for
  49563. */
  49564. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49565. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49566. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49567. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49568. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49569. };
  49570. /**
  49571. * Clones the current emitter and returns a copy of it
  49572. * @returns the new emitter
  49573. */
  49574. SphereDirectedParticleEmitter.prototype.clone = function () {
  49575. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  49576. BABYLON.Tools.DeepCopy(this, newOne);
  49577. return newOne;
  49578. };
  49579. return SphereDirectedParticleEmitter;
  49580. }(SphereParticleEmitter));
  49581. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  49582. })(BABYLON || (BABYLON = {}));
  49583. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  49584. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  49585. var BABYLON;
  49586. (function (BABYLON) {
  49587. /**
  49588. * This represents a GPU particle system in Babylon.
  49589. * This os the fastest particle system in Babylon as it uses the GPU to update the individual particle data.
  49590. */
  49591. var GPUParticleSystem = /** @class */ (function () {
  49592. /**
  49593. * Instantiates a GPU particle system.
  49594. * 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.
  49595. * @param name The name of the particle system
  49596. * @param capacity The max number of particles alive at the same time
  49597. * @param scene The scene the particle system belongs to
  49598. */
  49599. function GPUParticleSystem(name, capacity, scene) {
  49600. /**
  49601. * The emitter represents the Mesh or position we are attaching the particle system to.
  49602. */
  49603. this.emitter = null;
  49604. /**
  49605. * The rendering group used by the Particle system to chose when to render.
  49606. */
  49607. this.renderingGroupId = 0;
  49608. /**
  49609. * The layer mask we are rendering the particles through.
  49610. */
  49611. this.layerMask = 0x0FFFFFFF; // TODO
  49612. this._updateVertexBuffers = {};
  49613. this._renderVertexBuffers = {};
  49614. this._currentRenderId = -1;
  49615. this._started = true;
  49616. /**
  49617. * An event triggered when the system is disposed.
  49618. */
  49619. this.onDisposeObservable = new BABYLON.Observable();
  49620. this.id = name;
  49621. this.name = name;
  49622. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49623. this._capacity = capacity;
  49624. this._engine = this._scene.getEngine();
  49625. this._scene.particleSystems.push(this);
  49626. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  49627. var updateEffectOptions = {
  49628. attributes: ["position", "age", "life", "velocity"],
  49629. uniformsNames: [],
  49630. uniformBuffersNames: [],
  49631. samplers: [],
  49632. defines: "",
  49633. fallbacks: null,
  49634. onCompiled: null,
  49635. onError: null,
  49636. indexParameters: null,
  49637. maxSimultaneousLights: 0,
  49638. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  49639. };
  49640. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  49641. }
  49642. /**
  49643. * Gets Wether the system has been started.
  49644. * @returns True if it has been started, otherwise false.
  49645. */
  49646. GPUParticleSystem.prototype.isStarted = function () {
  49647. return this._started;
  49648. };
  49649. /**
  49650. * Starts the particle system and begins to emit.
  49651. */
  49652. GPUParticleSystem.prototype.start = function () {
  49653. this._started = true;
  49654. };
  49655. /**
  49656. * Stops the particle system.
  49657. */
  49658. GPUParticleSystem.prototype.stop = function () {
  49659. this._started = false;
  49660. };
  49661. /**
  49662. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  49663. */
  49664. GPUParticleSystem.prototype.animate = function () {
  49665. // Do nothing
  49666. };
  49667. GPUParticleSystem.prototype._initialize = function () {
  49668. if (this._renderVAO) {
  49669. return;
  49670. }
  49671. var data = new Array();
  49672. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  49673. // position
  49674. data.push(0.0);
  49675. data.push(0.0);
  49676. data.push(0.0);
  49677. var life = 1 + Math.random() * 10; // TODO: var
  49678. data.push(life + 1); // create the particle as a dead one to create a new one at start
  49679. data.push(life);
  49680. // velocity
  49681. data.push(0.0);
  49682. data.push(0.0);
  49683. data.push(0.0);
  49684. }
  49685. // Update VAO
  49686. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  49687. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  49688. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  49689. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  49690. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  49691. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  49692. this._engine.bindArrayBuffer(null);
  49693. // Render VAO
  49694. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  49695. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  49696. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  49697. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  49698. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  49699. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  49700. this._engine.bindArrayBuffer(null);
  49701. // Links
  49702. this._sourceVAO = this._updateVAO;
  49703. this._targetVAO = this._renderVAO;
  49704. this._sourceBuffer = this._updateBuffer;
  49705. this._targetBuffer = this._renderBuffer;
  49706. };
  49707. /**
  49708. * Renders the particle system in its current state.
  49709. * @returns the current number of particles.
  49710. */
  49711. GPUParticleSystem.prototype.render = function () {
  49712. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  49713. return 0;
  49714. }
  49715. // Get everything ready to render
  49716. this._initialize();
  49717. if (this._currentRenderId === this._scene.getRenderId()) {
  49718. return 0;
  49719. }
  49720. this._currentRenderId = this._scene.getRenderId();
  49721. // Enable update effect
  49722. this._engine.enableEffect(this._updateEffect);
  49723. this._engine.setState(false);
  49724. // Bind source VAO
  49725. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  49726. // Update
  49727. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  49728. this._engine.setRasterizerState(false);
  49729. this._engine.beginTransformFeedback();
  49730. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  49731. this._engine.endTransformFeedback();
  49732. this._engine.setRasterizerState(true);
  49733. this._engine.bindTransformFeedbackBuffer(null);
  49734. // Enable render effect
  49735. this._engine.enableEffect(this._renderEffect);
  49736. // Bind source VAO
  49737. this._engine.bindVertexArrayObject(this._targetVAO, null);
  49738. // Render
  49739. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  49740. // Switch VAOs
  49741. var tmpVAO = this._sourceVAO;
  49742. this._sourceVAO = this._targetVAO;
  49743. this._targetVAO = tmpVAO;
  49744. // Switch buffers
  49745. var tmpBuffer = this._sourceBuffer;
  49746. this._sourceBuffer = this._targetBuffer;
  49747. this._targetBuffer = tmpBuffer;
  49748. return 0;
  49749. };
  49750. /**
  49751. * Rebuilds the particle system
  49752. */
  49753. GPUParticleSystem.prototype.rebuild = function () {
  49754. };
  49755. /**
  49756. * Disposes the particle system and free the associated resources.
  49757. */
  49758. GPUParticleSystem.prototype.dispose = function () {
  49759. var index = this._scene.particleSystems.indexOf(this);
  49760. if (index > -1) {
  49761. this._scene.particleSystems.splice(index, 1);
  49762. }
  49763. //TODO: this._dataBuffer.dispose();
  49764. // Callback
  49765. this.onDisposeObservable.notifyObservers(this);
  49766. this.onDisposeObservable.clear();
  49767. };
  49768. //TODO: Clone / Parse / serialize
  49769. /**
  49770. * Clones the particle system.
  49771. * @param name The name of the cloned object
  49772. * @param newEmitter The new emitter to use
  49773. * @returns the cloned particle system
  49774. */
  49775. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  49776. return null;
  49777. };
  49778. /**
  49779. * Serializes the particle system to a JSON object.
  49780. * @returns the JSON object
  49781. */
  49782. GPUParticleSystem.prototype.serialize = function () {
  49783. };
  49784. return GPUParticleSystem;
  49785. }());
  49786. BABYLON.GPUParticleSystem = GPUParticleSystem;
  49787. })(BABYLON || (BABYLON = {}));
  49788. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  49789. var BABYLON;
  49790. (function (BABYLON) {
  49791. /**
  49792. * Represents one particle of a solid particle system.
  49793. * @see SolidParticleSystem
  49794. */
  49795. var SolidParticle = /** @class */ (function () {
  49796. /**
  49797. * Creates a Solid Particle object.
  49798. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49799. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49800. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49801. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  49802. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  49803. * @param shapeId (integer) is the model shape identifier in the SPS.
  49804. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49805. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  49806. */
  49807. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49808. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  49809. /**
  49810. * particle global index
  49811. */
  49812. this.idx = 0;
  49813. /**
  49814. * The color of the particle
  49815. */
  49816. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49817. /**
  49818. * The world space position of the particle.
  49819. */
  49820. this.position = BABYLON.Vector3.Zero();
  49821. /**
  49822. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  49823. */
  49824. this.rotation = BABYLON.Vector3.Zero();
  49825. /**
  49826. * The scaling of the particle.
  49827. */
  49828. this.scaling = BABYLON.Vector3.One();
  49829. /**
  49830. * The uvs of the particle.
  49831. */
  49832. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  49833. /**
  49834. * The current speed of the particle.
  49835. */
  49836. this.velocity = BABYLON.Vector3.Zero();
  49837. /**
  49838. * The pivot point in the particle local space.
  49839. */
  49840. this.pivot = BABYLON.Vector3.Zero();
  49841. /**
  49842. * Is the particle active or not ?
  49843. */
  49844. this.alive = true;
  49845. /**
  49846. * Is the particle visible or not ?
  49847. */
  49848. this.isVisible = true;
  49849. /**
  49850. * Index of this particle in the global "positions" array (Internal use)
  49851. */
  49852. this._pos = 0;
  49853. /**
  49854. * Index of this particle in the global "indices" array (Internal use)
  49855. */
  49856. this._ind = 0;
  49857. /**
  49858. * ModelShape id of this particle
  49859. */
  49860. this.shapeId = 0;
  49861. /**
  49862. * Index of the particle in its shape id (Internal use)
  49863. */
  49864. this.idxInShape = 0;
  49865. /**
  49866. * Still set as invisible in order to skip useless computations (Internal use)
  49867. */
  49868. this._stillInvisible = false;
  49869. /**
  49870. * Last computed particle rotation matrix
  49871. */
  49872. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  49873. this.idx = particleIndex;
  49874. this._pos = positionIndex;
  49875. this._ind = indiceIndex;
  49876. this._model = model;
  49877. this.shapeId = shapeId;
  49878. this.idxInShape = idxInShape;
  49879. this._sps = sps;
  49880. if (modelBoundingInfo) {
  49881. this._modelBoundingInfo = modelBoundingInfo;
  49882. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49883. }
  49884. }
  49885. Object.defineProperty(SolidParticle.prototype, "scale", {
  49886. /**
  49887. * Legacy support, changed scale to scaling
  49888. */
  49889. get: function () {
  49890. return this.scaling;
  49891. },
  49892. /**
  49893. * Legacy support, changed scale to scaling
  49894. */
  49895. set: function (scale) {
  49896. this.scaling = scale;
  49897. },
  49898. enumerable: true,
  49899. configurable: true
  49900. });
  49901. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49902. /**
  49903. * Legacy support, changed quaternion to rotationQuaternion
  49904. */
  49905. get: function () {
  49906. return this.rotationQuaternion;
  49907. },
  49908. /**
  49909. * Legacy support, changed quaternion to rotationQuaternion
  49910. */
  49911. set: function (q) {
  49912. this.rotationQuaternion = q;
  49913. },
  49914. enumerable: true,
  49915. configurable: true
  49916. });
  49917. /**
  49918. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49919. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49920. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  49921. * @returns true if it intersects
  49922. */
  49923. SolidParticle.prototype.intersectsMesh = function (target) {
  49924. if (!this._boundingInfo || !target._boundingInfo) {
  49925. return false;
  49926. }
  49927. if (this._sps._bSphereOnly) {
  49928. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49929. }
  49930. return this._boundingInfo.intersects(target._boundingInfo, false);
  49931. };
  49932. return SolidParticle;
  49933. }());
  49934. BABYLON.SolidParticle = SolidParticle;
  49935. /**
  49936. * Represents the shape of the model used by one particle of a solid particle system.
  49937. * SPS internal tool, don't use it manually.
  49938. * @see SolidParticleSystem
  49939. */
  49940. var ModelShape = /** @class */ (function () {
  49941. /**
  49942. * 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.
  49943. * SPS internal tool, don't use it manually.
  49944. * @ignore
  49945. */
  49946. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  49947. /**
  49948. * length of the shape in the model indices array (internal use)
  49949. */
  49950. this._indicesLength = 0;
  49951. this.shapeID = id;
  49952. this._shape = shape;
  49953. this._indicesLength = indicesLength;
  49954. this._shapeUV = shapeUV;
  49955. this._positionFunction = posFunction;
  49956. this._vertexFunction = vtxFunction;
  49957. }
  49958. return ModelShape;
  49959. }());
  49960. BABYLON.ModelShape = ModelShape;
  49961. /**
  49962. * Represents a Depth Sorted Particle in the solid particle system.
  49963. * @see SolidParticleSystem
  49964. */
  49965. var DepthSortedParticle = /** @class */ (function () {
  49966. function DepthSortedParticle() {
  49967. /**
  49968. * Index of the particle in the "indices" array
  49969. */
  49970. this.ind = 0;
  49971. /**
  49972. * Length of the particle shape in the "indices" array
  49973. */
  49974. this.indicesLength = 0;
  49975. /**
  49976. * Squared distance from the particle to the camera
  49977. */
  49978. this.sqDistance = 0.0;
  49979. }
  49980. return DepthSortedParticle;
  49981. }());
  49982. BABYLON.DepthSortedParticle = DepthSortedParticle;
  49983. })(BABYLON || (BABYLON = {}));
  49984. //# sourceMappingURL=babylon.solidParticle.js.map
  49985. var BABYLON;
  49986. (function (BABYLON) {
  49987. /**
  49988. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  49989. *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.
  49990. * The SPS is also a particle system. It provides some methods to manage the particles.
  49991. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  49992. *
  49993. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49994. */
  49995. var SolidParticleSystem = /** @class */ (function () {
  49996. /**
  49997. * Creates a SPS (Solid Particle System) object.
  49998. * @param name (String) is the SPS name, this will be the underlying mesh name.
  49999. * @param scene (Scene) is the scene in which the SPS is added.
  50000. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  50001. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  50002. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  50003. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  50004. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  50005. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  50006. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  50007. */
  50008. function SolidParticleSystem(name, scene, options) {
  50009. /**
  50010. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  50011. * Example : var p = SPS.particles[i];
  50012. */
  50013. this.particles = new Array();
  50014. /**
  50015. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  50016. */
  50017. this.nbParticles = 0;
  50018. /**
  50019. * If the particles must ever face the camera (default false). Useful for planar particles.
  50020. */
  50021. this.billboard = false;
  50022. /**
  50023. * Recompute normals when adding a shape
  50024. */
  50025. this.recomputeNormals = true;
  50026. /**
  50027. * This a counter ofr your own usage. It's not set by any SPS functions.
  50028. */
  50029. this.counter = 0;
  50030. /**
  50031. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  50032. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  50033. */
  50034. this.vars = {};
  50035. /**
  50036. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  50037. */
  50038. this._bSphereOnly = false;
  50039. /**
  50040. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  50041. */
  50042. this._bSphereRadiusFactor = 1.0;
  50043. this._positions = new Array();
  50044. this._indices = new Array();
  50045. this._normals = new Array();
  50046. this._colors = new Array();
  50047. this._uvs = new Array();
  50048. this._index = 0; // indices index
  50049. this._updatable = true;
  50050. this._pickable = false;
  50051. this._isVisibilityBoxLocked = false;
  50052. this._alwaysVisible = false;
  50053. this._depthSort = false;
  50054. this._shapeCounter = 0;
  50055. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  50056. this._color = new BABYLON.Color4(0, 0, 0, 0);
  50057. this._computeParticleColor = true;
  50058. this._computeParticleTexture = true;
  50059. this._computeParticleRotation = true;
  50060. this._computeParticleVertex = false;
  50061. this._computeBoundingBox = false;
  50062. this._depthSortParticles = true;
  50063. this._cam_axisZ = BABYLON.Vector3.Zero();
  50064. this._cam_axisY = BABYLON.Vector3.Zero();
  50065. this._cam_axisX = BABYLON.Vector3.Zero();
  50066. this._axisZ = BABYLON.Axis.Z;
  50067. this._camDir = BABYLON.Vector3.Zero();
  50068. this._camInvertedPosition = BABYLON.Vector3.Zero();
  50069. this._rotMatrix = new BABYLON.Matrix();
  50070. this._invertMatrix = new BABYLON.Matrix();
  50071. this._rotated = BABYLON.Vector3.Zero();
  50072. this._quaternion = new BABYLON.Quaternion();
  50073. this._vertex = BABYLON.Vector3.Zero();
  50074. this._normal = BABYLON.Vector3.Zero();
  50075. this._yaw = 0.0;
  50076. this._pitch = 0.0;
  50077. this._roll = 0.0;
  50078. this._halfroll = 0.0;
  50079. this._halfpitch = 0.0;
  50080. this._halfyaw = 0.0;
  50081. this._sinRoll = 0.0;
  50082. this._cosRoll = 0.0;
  50083. this._sinPitch = 0.0;
  50084. this._cosPitch = 0.0;
  50085. this._sinYaw = 0.0;
  50086. this._cosYaw = 0.0;
  50087. this._mustUnrotateFixedNormals = false;
  50088. this._minimum = BABYLON.Tmp.Vector3[0];
  50089. this._maximum = BABYLON.Tmp.Vector3[1];
  50090. this._minBbox = BABYLON.Tmp.Vector3[4];
  50091. this._maxBbox = BABYLON.Tmp.Vector3[5];
  50092. this._particlesIntersect = false;
  50093. this._depthSortFunction = function (p1, p2) {
  50094. return (p2.sqDistance - p1.sqDistance);
  50095. };
  50096. this._needs32Bits = false;
  50097. this.name = name;
  50098. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50099. this._camera = scene.activeCamera;
  50100. this._pickable = options ? options.isPickable : false;
  50101. this._depthSort = options ? options.enableDepthSort : false;
  50102. this._particlesIntersect = options ? options.particleIntersection : false;
  50103. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  50104. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  50105. if (options && options.updatable) {
  50106. this._updatable = options.updatable;
  50107. }
  50108. else {
  50109. this._updatable = true;
  50110. }
  50111. if (this._pickable) {
  50112. this.pickedParticles = [];
  50113. }
  50114. if (this._depthSort) {
  50115. this.depthSortedParticles = [];
  50116. }
  50117. }
  50118. /**
  50119. * Builds the SPS underlying mesh. Returns a standard Mesh.
  50120. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  50121. * @returns the created mesh
  50122. */
  50123. SolidParticleSystem.prototype.buildMesh = function () {
  50124. if (this.nbParticles === 0) {
  50125. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  50126. this.addShape(triangle, 1);
  50127. triangle.dispose();
  50128. }
  50129. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  50130. this._positions32 = new Float32Array(this._positions);
  50131. this._uvs32 = new Float32Array(this._uvs);
  50132. this._colors32 = new Float32Array(this._colors);
  50133. if (this.recomputeNormals) {
  50134. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  50135. }
  50136. this._normals32 = new Float32Array(this._normals);
  50137. this._fixedNormal32 = new Float32Array(this._normals);
  50138. if (this._mustUnrotateFixedNormals) {
  50139. this._unrotateFixedNormals();
  50140. }
  50141. var vertexData = new BABYLON.VertexData();
  50142. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  50143. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  50144. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  50145. if (this._uvs32) {
  50146. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  50147. ;
  50148. }
  50149. if (this._colors32) {
  50150. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  50151. }
  50152. var mesh = new BABYLON.Mesh(this.name, this._scene);
  50153. vertexData.applyToMesh(mesh, this._updatable);
  50154. this.mesh = mesh;
  50155. this.mesh.isPickable = this._pickable;
  50156. // free memory
  50157. if (!this._depthSort) {
  50158. this._indices = null;
  50159. }
  50160. this._positions = null;
  50161. this._normals = null;
  50162. this._uvs = null;
  50163. this._colors = null;
  50164. if (!this._updatable) {
  50165. this.particles.length = 0;
  50166. }
  50167. return mesh;
  50168. };
  50169. /**
  50170. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  50171. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  50172. * Thus the particles generated from `digest()` have their property `position` set yet.
  50173. * @param mesh ( Mesh ) is the mesh to be digested
  50174. * @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
  50175. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  50176. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  50177. * @returns the current SPS
  50178. */
  50179. SolidParticleSystem.prototype.digest = function (mesh, options) {
  50180. var size = (options && options.facetNb) || 1;
  50181. var number = (options && options.number) || 0;
  50182. var delta = (options && options.delta) || 0;
  50183. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50184. var meshInd = mesh.getIndices();
  50185. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50186. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50187. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50188. var f = 0; // facet counter
  50189. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  50190. // compute size from number
  50191. if (number) {
  50192. number = (number > totalFacets) ? totalFacets : number;
  50193. size = Math.round(totalFacets / number);
  50194. delta = 0;
  50195. }
  50196. else {
  50197. size = (size > totalFacets) ? totalFacets : size;
  50198. }
  50199. var facetPos = []; // submesh positions
  50200. var facetInd = []; // submesh indices
  50201. var facetUV = []; // submesh UV
  50202. var facetCol = []; // submesh colors
  50203. var barycenter = BABYLON.Tmp.Vector3[0];
  50204. var sizeO = size;
  50205. while (f < totalFacets) {
  50206. size = sizeO + Math.floor((1 + delta) * Math.random());
  50207. if (f > totalFacets - size) {
  50208. size = totalFacets - f;
  50209. }
  50210. // reset temp arrays
  50211. facetPos.length = 0;
  50212. facetInd.length = 0;
  50213. facetUV.length = 0;
  50214. facetCol.length = 0;
  50215. // iterate over "size" facets
  50216. var fi = 0;
  50217. for (var j = f * 3; j < (f + size) * 3; j++) {
  50218. facetInd.push(fi);
  50219. var i = meshInd[j];
  50220. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  50221. if (meshUV) {
  50222. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  50223. }
  50224. if (meshCol) {
  50225. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  50226. }
  50227. fi++;
  50228. }
  50229. // create a model shape for each single particle
  50230. var idx = this.nbParticles;
  50231. var shape = this._posToShape(facetPos);
  50232. var shapeUV = this._uvsToShapeUV(facetUV);
  50233. // compute the barycenter of the shape
  50234. var v;
  50235. for (v = 0; v < shape.length; v++) {
  50236. barycenter.addInPlace(shape[v]);
  50237. }
  50238. barycenter.scaleInPlace(1 / shape.length);
  50239. // shift the shape from its barycenter to the origin
  50240. for (v = 0; v < shape.length; v++) {
  50241. shape[v].subtractInPlace(barycenter);
  50242. }
  50243. var bInfo;
  50244. if (this._particlesIntersect) {
  50245. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  50246. }
  50247. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  50248. // add the particle in the SPS
  50249. var currentPos = this._positions.length;
  50250. var currentInd = this._indices.length;
  50251. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  50252. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  50253. // initialize the particle position
  50254. this.particles[this.nbParticles].position.addInPlace(barycenter);
  50255. this._index += shape.length;
  50256. idx++;
  50257. this.nbParticles++;
  50258. this._shapeCounter++;
  50259. f += size;
  50260. }
  50261. return this;
  50262. };
  50263. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  50264. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  50265. var index = 0;
  50266. var idx = 0;
  50267. for (var p = 0; p < this.particles.length; p++) {
  50268. this._particle = this.particles[p];
  50269. this._shape = this._particle._model._shape;
  50270. if (this._particle.rotationQuaternion) {
  50271. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50272. }
  50273. else {
  50274. this._yaw = this._particle.rotation.y;
  50275. this._pitch = this._particle.rotation.x;
  50276. this._roll = this._particle.rotation.z;
  50277. this._quaternionRotationYPR();
  50278. }
  50279. this._quaternionToRotationMatrix();
  50280. this._rotMatrix.invertToRef(this._invertMatrix);
  50281. for (var pt = 0; pt < this._shape.length; pt++) {
  50282. idx = index + pt * 3;
  50283. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  50284. this._fixedNormal32[idx] = this._normal.x;
  50285. this._fixedNormal32[idx + 1] = this._normal.y;
  50286. this._fixedNormal32[idx + 2] = this._normal.z;
  50287. }
  50288. index = idx + 3;
  50289. }
  50290. };
  50291. //reset copy
  50292. SolidParticleSystem.prototype._resetCopy = function () {
  50293. this._copy.position.x = 0;
  50294. this._copy.position.y = 0;
  50295. this._copy.position.z = 0;
  50296. this._copy.rotation.x = 0;
  50297. this._copy.rotation.y = 0;
  50298. this._copy.rotation.z = 0;
  50299. this._copy.rotationQuaternion = null;
  50300. this._copy.scaling.x = 1.0;
  50301. this._copy.scaling.y = 1.0;
  50302. this._copy.scaling.z = 1.0;
  50303. this._copy.uvs.x = 0;
  50304. this._copy.uvs.y = 0;
  50305. this._copy.uvs.z = 1.0;
  50306. this._copy.uvs.w = 1.0;
  50307. this._copy.color = null;
  50308. };
  50309. // _meshBuilder : inserts the shape model in the global SPS mesh
  50310. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  50311. var i;
  50312. var u = 0;
  50313. var c = 0;
  50314. var n = 0;
  50315. this._resetCopy();
  50316. if (options && options.positionFunction) {
  50317. options.positionFunction(this._copy, idx, idxInShape);
  50318. this._mustUnrotateFixedNormals = true;
  50319. }
  50320. if (this._copy.rotationQuaternion) {
  50321. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50322. }
  50323. else {
  50324. this._yaw = this._copy.rotation.y;
  50325. this._pitch = this._copy.rotation.x;
  50326. this._roll = this._copy.rotation.z;
  50327. this._quaternionRotationYPR();
  50328. }
  50329. this._quaternionToRotationMatrix();
  50330. for (i = 0; i < shape.length; i++) {
  50331. this._vertex.x = shape[i].x;
  50332. this._vertex.y = shape[i].y;
  50333. this._vertex.z = shape[i].z;
  50334. if (options && options.vertexFunction) {
  50335. options.vertexFunction(this._copy, this._vertex, i);
  50336. }
  50337. this._vertex.x *= this._copy.scaling.x;
  50338. this._vertex.y *= this._copy.scaling.y;
  50339. this._vertex.z *= this._copy.scaling.z;
  50340. this._vertex.x += this._copy.pivot.x;
  50341. this._vertex.y += this._copy.pivot.y;
  50342. this._vertex.z += this._copy.pivot.z;
  50343. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50344. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  50345. if (meshUV) {
  50346. 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);
  50347. u += 2;
  50348. }
  50349. if (this._copy.color) {
  50350. this._color = this._copy.color;
  50351. }
  50352. else if (meshCol && meshCol[c] !== undefined) {
  50353. this._color.r = meshCol[c];
  50354. this._color.g = meshCol[c + 1];
  50355. this._color.b = meshCol[c + 2];
  50356. this._color.a = meshCol[c + 3];
  50357. }
  50358. else {
  50359. this._color.r = 1.0;
  50360. this._color.g = 1.0;
  50361. this._color.b = 1.0;
  50362. this._color.a = 1.0;
  50363. }
  50364. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  50365. c += 4;
  50366. if (!this.recomputeNormals && meshNor) {
  50367. this._normal.x = meshNor[n];
  50368. this._normal.y = meshNor[n + 1];
  50369. this._normal.z = meshNor[n + 2];
  50370. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  50371. normals.push(this._normal.x, this._normal.y, this._normal.z);
  50372. n += 3;
  50373. }
  50374. }
  50375. for (i = 0; i < meshInd.length; i++) {
  50376. var current_ind = p + meshInd[i];
  50377. indices.push(current_ind);
  50378. if (current_ind > 65535) {
  50379. this._needs32Bits = true;
  50380. }
  50381. }
  50382. if (this._pickable) {
  50383. var nbfaces = meshInd.length / 3;
  50384. for (i = 0; i < nbfaces; i++) {
  50385. this.pickedParticles.push({ idx: idx, faceId: i });
  50386. }
  50387. }
  50388. if (this._depthSort) {
  50389. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  50390. }
  50391. return this._copy;
  50392. };
  50393. // returns a shape array from positions array
  50394. SolidParticleSystem.prototype._posToShape = function (positions) {
  50395. var shape = [];
  50396. for (var i = 0; i < positions.length; i += 3) {
  50397. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  50398. }
  50399. return shape;
  50400. };
  50401. // returns a shapeUV array from a Vector4 uvs
  50402. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  50403. var shapeUV = [];
  50404. if (uvs) {
  50405. for (var i = 0; i < uvs.length; i++)
  50406. shapeUV.push(uvs[i]);
  50407. }
  50408. return shapeUV;
  50409. };
  50410. // adds a new particle object in the particles array
  50411. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  50412. if (bInfo === void 0) { bInfo = null; }
  50413. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  50414. this.particles.push(sp);
  50415. return sp;
  50416. };
  50417. /**
  50418. * Adds some particles to the SPS from the model shape. Returns the shape id.
  50419. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  50420. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  50421. * @param nb (positive integer) the number of particles to be created from this model
  50422. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  50423. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  50424. * @returns the number of shapes in the system
  50425. */
  50426. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  50427. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50428. var meshInd = mesh.getIndices();
  50429. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50430. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50431. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50432. var bbInfo;
  50433. if (this._particlesIntersect) {
  50434. bbInfo = mesh.getBoundingInfo();
  50435. }
  50436. var shape = this._posToShape(meshPos);
  50437. var shapeUV = this._uvsToShapeUV(meshUV);
  50438. var posfunc = options ? options.positionFunction : null;
  50439. var vtxfunc = options ? options.vertexFunction : null;
  50440. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  50441. // particles
  50442. var sp;
  50443. var currentCopy;
  50444. var idx = this.nbParticles;
  50445. for (var i = 0; i < nb; i++) {
  50446. var currentPos = this._positions.length;
  50447. var currentInd = this._indices.length;
  50448. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  50449. if (this._updatable) {
  50450. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  50451. sp.position.copyFrom(currentCopy.position);
  50452. sp.rotation.copyFrom(currentCopy.rotation);
  50453. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  50454. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  50455. }
  50456. if (currentCopy.color && sp.color) {
  50457. sp.color.copyFrom(currentCopy.color);
  50458. }
  50459. sp.scaling.copyFrom(currentCopy.scaling);
  50460. sp.uvs.copyFrom(currentCopy.uvs);
  50461. }
  50462. this._index += shape.length;
  50463. idx++;
  50464. }
  50465. this.nbParticles += nb;
  50466. this._shapeCounter++;
  50467. return this._shapeCounter - 1;
  50468. };
  50469. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  50470. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  50471. this._resetCopy();
  50472. if (particle._model._positionFunction) {
  50473. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  50474. }
  50475. if (this._copy.rotationQuaternion) {
  50476. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50477. }
  50478. else {
  50479. this._yaw = this._copy.rotation.y;
  50480. this._pitch = this._copy.rotation.x;
  50481. this._roll = this._copy.rotation.z;
  50482. this._quaternionRotationYPR();
  50483. }
  50484. this._quaternionToRotationMatrix();
  50485. this._shape = particle._model._shape;
  50486. for (var pt = 0; pt < this._shape.length; pt++) {
  50487. this._vertex.x = this._shape[pt].x;
  50488. this._vertex.y = this._shape[pt].y;
  50489. this._vertex.z = this._shape[pt].z;
  50490. if (particle._model._vertexFunction) {
  50491. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  50492. }
  50493. this._vertex.x *= this._copy.scaling.x;
  50494. this._vertex.y *= this._copy.scaling.y;
  50495. this._vertex.z *= this._copy.scaling.z;
  50496. this._vertex.x += this._copy.pivot.x;
  50497. this._vertex.y += this._copy.pivot.y;
  50498. this._vertex.z += this._copy.pivot.z;
  50499. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50500. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  50501. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  50502. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  50503. }
  50504. particle.position.x = 0.0;
  50505. particle.position.y = 0.0;
  50506. particle.position.z = 0.0;
  50507. particle.rotation.x = 0.0;
  50508. particle.rotation.y = 0.0;
  50509. particle.rotation.z = 0.0;
  50510. particle.rotationQuaternion = null;
  50511. particle.scaling.x = 1.0;
  50512. particle.scaling.y = 1.0;
  50513. particle.scaling.z = 1.0;
  50514. };
  50515. /**
  50516. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  50517. * @returns the SPS.
  50518. */
  50519. SolidParticleSystem.prototype.rebuildMesh = function () {
  50520. for (var p = 0; p < this.particles.length; p++) {
  50521. this._rebuildParticle(this.particles[p]);
  50522. }
  50523. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50524. return this;
  50525. };
  50526. /**
  50527. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  50528. * This method calls `updateParticle()` for each particle of the SPS.
  50529. * For an animated SPS, it is usually called within the render loop.
  50530. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  50531. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  50532. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  50533. * @returns the SPS.
  50534. */
  50535. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  50536. if (start === void 0) { start = 0; }
  50537. if (end === void 0) { end = this.nbParticles - 1; }
  50538. if (update === void 0) { update = true; }
  50539. if (!this._updatable) {
  50540. return this;
  50541. }
  50542. // custom beforeUpdate
  50543. this.beforeUpdateParticles(start, end, update);
  50544. this._cam_axisX.x = 1.0;
  50545. this._cam_axisX.y = 0.0;
  50546. this._cam_axisX.z = 0.0;
  50547. this._cam_axisY.x = 0.0;
  50548. this._cam_axisY.y = 1.0;
  50549. this._cam_axisY.z = 0.0;
  50550. this._cam_axisZ.x = 0.0;
  50551. this._cam_axisZ.y = 0.0;
  50552. this._cam_axisZ.z = 1.0;
  50553. // cases when the World Matrix is to be computed first
  50554. if (this.billboard || this._depthSort) {
  50555. this.mesh.computeWorldMatrix(true);
  50556. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  50557. }
  50558. // if the particles will always face the camera
  50559. if (this.billboard) {
  50560. // compute the camera position and un-rotate it by the current mesh rotation
  50561. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  50562. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  50563. this._cam_axisZ.normalize();
  50564. // same for camera up vector extracted from the cam view matrix
  50565. var view = this._camera.getViewMatrix(true);
  50566. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  50567. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  50568. this._cam_axisY.normalize();
  50569. this._cam_axisX.normalize();
  50570. }
  50571. // if depthSort, compute the camera global position in the mesh local system
  50572. if (this._depthSort) {
  50573. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  50574. }
  50575. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  50576. var idx = 0; // current position index in the global array positions32
  50577. var index = 0; // position start index in the global array positions32 of the current particle
  50578. var colidx = 0; // current color index in the global array colors32
  50579. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  50580. var uvidx = 0; // current uv index in the global array uvs32
  50581. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  50582. var pt = 0; // current index in the particle model shape
  50583. if (this.mesh.isFacetDataEnabled) {
  50584. this._computeBoundingBox = true;
  50585. }
  50586. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  50587. if (this._computeBoundingBox) {
  50588. if (start == 0 && end == this.nbParticles - 1) {
  50589. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  50590. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  50591. }
  50592. else {
  50593. if (this.mesh._boundingInfo) {
  50594. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  50595. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  50596. }
  50597. }
  50598. }
  50599. // particle loop
  50600. index = this.particles[start]._pos;
  50601. var vpos = (index / 3) | 0;
  50602. colorIndex = vpos * 4;
  50603. uvIndex = vpos * 2;
  50604. for (var p = start; p <= end; p++) {
  50605. this._particle = this.particles[p];
  50606. this._shape = this._particle._model._shape;
  50607. this._shapeUV = this._particle._model._shapeUV;
  50608. // call to custom user function to update the particle properties
  50609. this.updateParticle(this._particle);
  50610. // camera-particle distance for depth sorting
  50611. if (this._depthSort && this._depthSortParticles) {
  50612. var dsp = this.depthSortedParticles[p];
  50613. dsp.ind = this._particle._ind;
  50614. dsp.indicesLength = this._particle._model._indicesLength;
  50615. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  50616. }
  50617. // skip the computations for inactive or already invisible particles
  50618. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  50619. // increment indexes for the next particle
  50620. pt = this._shape.length;
  50621. index += pt * 3;
  50622. colorIndex += pt * 4;
  50623. uvIndex += pt * 2;
  50624. continue;
  50625. }
  50626. if (this._particle.isVisible) {
  50627. this._particle._stillInvisible = false; // un-mark permanent invisibility
  50628. // particle rotation matrix
  50629. if (this.billboard) {
  50630. this._particle.rotation.x = 0.0;
  50631. this._particle.rotation.y = 0.0;
  50632. }
  50633. if (this._computeParticleRotation || this.billboard) {
  50634. if (this._particle.rotationQuaternion) {
  50635. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50636. }
  50637. else {
  50638. this._yaw = this._particle.rotation.y;
  50639. this._pitch = this._particle.rotation.x;
  50640. this._roll = this._particle.rotation.z;
  50641. this._quaternionRotationYPR();
  50642. }
  50643. this._quaternionToRotationMatrix();
  50644. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  50645. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  50646. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  50647. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  50648. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  50649. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  50650. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  50651. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  50652. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  50653. }
  50654. // particle vertex loop
  50655. for (pt = 0; pt < this._shape.length; pt++) {
  50656. idx = index + pt * 3;
  50657. colidx = colorIndex + pt * 4;
  50658. uvidx = uvIndex + pt * 2;
  50659. this._vertex.x = this._shape[pt].x;
  50660. this._vertex.y = this._shape[pt].y;
  50661. this._vertex.z = this._shape[pt].z;
  50662. if (this._computeParticleVertex) {
  50663. this.updateParticleVertex(this._particle, this._vertex, pt);
  50664. }
  50665. // positions
  50666. this._vertex.x *= this._particle.scaling.x;
  50667. this._vertex.y *= this._particle.scaling.y;
  50668. this._vertex.z *= this._particle.scaling.z;
  50669. this._vertex.x += this._particle.pivot.x;
  50670. this._vertex.y += this._particle.pivot.y;
  50671. this._vertex.z += this._particle.pivot.z;
  50672. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50673. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50674. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50675. 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;
  50676. 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;
  50677. 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;
  50678. if (this._computeBoundingBox) {
  50679. if (this._positions32[idx] < this._minimum.x) {
  50680. this._minimum.x = this._positions32[idx];
  50681. }
  50682. if (this._positions32[idx] > this._maximum.x) {
  50683. this._maximum.x = this._positions32[idx];
  50684. }
  50685. if (this._positions32[idx + 1] < this._minimum.y) {
  50686. this._minimum.y = this._positions32[idx + 1];
  50687. }
  50688. if (this._positions32[idx + 1] > this._maximum.y) {
  50689. this._maximum.y = this._positions32[idx + 1];
  50690. }
  50691. if (this._positions32[idx + 2] < this._minimum.z) {
  50692. this._minimum.z = this._positions32[idx + 2];
  50693. }
  50694. if (this._positions32[idx + 2] > this._maximum.z) {
  50695. this._maximum.z = this._positions32[idx + 2];
  50696. }
  50697. }
  50698. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  50699. if (!this._computeParticleVertex) {
  50700. this._normal.x = this._fixedNormal32[idx];
  50701. this._normal.y = this._fixedNormal32[idx + 1];
  50702. this._normal.z = this._fixedNormal32[idx + 2];
  50703. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  50704. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  50705. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  50706. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  50707. 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;
  50708. 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;
  50709. }
  50710. if (this._computeParticleColor && this._particle.color) {
  50711. this._colors32[colidx] = this._particle.color.r;
  50712. this._colors32[colidx + 1] = this._particle.color.g;
  50713. this._colors32[colidx + 2] = this._particle.color.b;
  50714. this._colors32[colidx + 3] = this._particle.color.a;
  50715. }
  50716. if (this._computeParticleTexture) {
  50717. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50718. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50719. }
  50720. }
  50721. }
  50722. else {
  50723. this._particle._stillInvisible = true; // mark the particle as invisible
  50724. for (pt = 0; pt < this._shape.length; pt++) {
  50725. idx = index + pt * 3;
  50726. colidx = colorIndex + pt * 4;
  50727. uvidx = uvIndex + pt * 2;
  50728. this._positions32[idx] = 0.0;
  50729. this._positions32[idx + 1] = 0.0;
  50730. this._positions32[idx + 2] = 0.0;
  50731. this._normals32[idx] = 0.0;
  50732. this._normals32[idx + 1] = 0.0;
  50733. this._normals32[idx + 2] = 0.0;
  50734. if (this._computeParticleColor && this._particle.color) {
  50735. this._colors32[colidx] = this._particle.color.r;
  50736. this._colors32[colidx + 1] = this._particle.color.g;
  50737. this._colors32[colidx + 2] = this._particle.color.b;
  50738. this._colors32[colidx + 3] = this._particle.color.a;
  50739. }
  50740. if (this._computeParticleTexture) {
  50741. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50742. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50743. }
  50744. }
  50745. }
  50746. // if the particle intersections must be computed : update the bbInfo
  50747. if (this._particlesIntersect) {
  50748. var bInfo = this._particle._boundingInfo;
  50749. var bBox = bInfo.boundingBox;
  50750. var bSphere = bInfo.boundingSphere;
  50751. if (!this._bSphereOnly) {
  50752. // place, scale and rotate the particle bbox within the SPS local system, then update it
  50753. for (var b = 0; b < bBox.vectors.length; b++) {
  50754. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  50755. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  50756. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  50757. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50758. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50759. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50760. 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;
  50761. 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;
  50762. 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;
  50763. }
  50764. bBox._update(this.mesh._worldMatrix);
  50765. }
  50766. // place and scale the particle bouding sphere in the SPS local system, then update it
  50767. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50768. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50769. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50770. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50771. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50772. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50773. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50774. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50775. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50776. 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));
  50777. bSphere._update(this.mesh._worldMatrix);
  50778. }
  50779. // increment indexes for the next particle
  50780. index = idx + 3;
  50781. colorIndex = colidx + 4;
  50782. uvIndex = uvidx + 2;
  50783. }
  50784. // if the VBO must be updated
  50785. if (update) {
  50786. if (this._computeParticleColor) {
  50787. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50788. }
  50789. if (this._computeParticleTexture) {
  50790. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50791. }
  50792. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50793. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  50794. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  50795. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50796. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  50797. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  50798. for (var i = 0; i < this._normals32.length; i++) {
  50799. this._fixedNormal32[i] = this._normals32[i];
  50800. }
  50801. }
  50802. if (!this.mesh.areNormalsFrozen) {
  50803. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50804. }
  50805. }
  50806. if (this._depthSort && this._depthSortParticles) {
  50807. this.depthSortedParticles.sort(this._depthSortFunction);
  50808. var dspl = this.depthSortedParticles.length;
  50809. var sorted = 0;
  50810. var lind = 0;
  50811. var sind = 0;
  50812. var sid = 0;
  50813. for (sorted = 0; sorted < dspl; sorted++) {
  50814. lind = this.depthSortedParticles[sorted].indicesLength;
  50815. sind = this.depthSortedParticles[sorted].ind;
  50816. for (var i = 0; i < lind; i++) {
  50817. this._indices32[sid] = this._indices[sind + i];
  50818. sid++;
  50819. }
  50820. }
  50821. this.mesh.updateIndices(this._indices32);
  50822. }
  50823. }
  50824. if (this._computeBoundingBox) {
  50825. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50826. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50827. }
  50828. this.afterUpdateParticles(start, end, update);
  50829. return this;
  50830. };
  50831. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50832. this._halfroll = this._roll * 0.5;
  50833. this._halfpitch = this._pitch * 0.5;
  50834. this._halfyaw = this._yaw * 0.5;
  50835. this._sinRoll = Math.sin(this._halfroll);
  50836. this._cosRoll = Math.cos(this._halfroll);
  50837. this._sinPitch = Math.sin(this._halfpitch);
  50838. this._cosPitch = Math.cos(this._halfpitch);
  50839. this._sinYaw = Math.sin(this._halfyaw);
  50840. this._cosYaw = Math.cos(this._halfyaw);
  50841. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  50842. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  50843. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  50844. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  50845. };
  50846. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50847. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50848. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50849. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50850. this._rotMatrix.m[3] = 0;
  50851. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50852. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50853. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50854. this._rotMatrix.m[7] = 0;
  50855. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50856. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50857. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50858. this._rotMatrix.m[11] = 0;
  50859. this._rotMatrix.m[12] = 0;
  50860. this._rotMatrix.m[13] = 0;
  50861. this._rotMatrix.m[14] = 0;
  50862. this._rotMatrix.m[15] = 1.0;
  50863. };
  50864. /**
  50865. * Disposes the SPS.
  50866. */
  50867. SolidParticleSystem.prototype.dispose = function () {
  50868. this.mesh.dispose();
  50869. this.vars = null;
  50870. // drop references to internal big arrays for the GC
  50871. this._positions = null;
  50872. this._indices = null;
  50873. this._normals = null;
  50874. this._uvs = null;
  50875. this._colors = null;
  50876. this._indices32 = null;
  50877. this._positions32 = null;
  50878. this._normals32 = null;
  50879. this._fixedNormal32 = null;
  50880. this._uvs32 = null;
  50881. this._colors32 = null;
  50882. this.pickedParticles = null;
  50883. };
  50884. /**
  50885. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50886. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50887. * @returns the SPS.
  50888. */
  50889. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50890. if (!this._isVisibilityBoxLocked) {
  50891. this.mesh.refreshBoundingInfo();
  50892. }
  50893. return this;
  50894. };
  50895. /**
  50896. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50897. * @param size the size (float) of the visibility box
  50898. * note : this doesn't lock the SPS mesh bounding box.
  50899. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50900. */
  50901. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50902. var vis = size / 2;
  50903. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50904. };
  50905. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50906. /**
  50907. * Gets whether the SPS as always visible or not
  50908. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50909. */
  50910. get: function () {
  50911. return this._alwaysVisible;
  50912. },
  50913. /**
  50914. * Sets the SPS as always visible or not
  50915. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50916. */
  50917. set: function (val) {
  50918. this._alwaysVisible = val;
  50919. this.mesh.alwaysSelectAsActiveMesh = val;
  50920. },
  50921. enumerable: true,
  50922. configurable: true
  50923. });
  50924. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50925. /**
  50926. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50927. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50928. */
  50929. get: function () {
  50930. return this._isVisibilityBoxLocked;
  50931. },
  50932. /**
  50933. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50934. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50935. */
  50936. set: function (val) {
  50937. this._isVisibilityBoxLocked = val;
  50938. var boundingInfo = this.mesh.getBoundingInfo();
  50939. boundingInfo.isLocked = val;
  50940. },
  50941. enumerable: true,
  50942. configurable: true
  50943. });
  50944. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50945. /**
  50946. * Gets if `setParticles()` computes the particle rotations or not.
  50947. * Default value : true. The SPS is faster when it's set to false.
  50948. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50949. */
  50950. get: function () {
  50951. return this._computeParticleRotation;
  50952. },
  50953. /**
  50954. * Tells to `setParticles()` to compute the particle rotations or not.
  50955. * Default value : true. The SPS is faster when it's set to false.
  50956. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50957. */
  50958. set: function (val) {
  50959. this._computeParticleRotation = val;
  50960. },
  50961. enumerable: true,
  50962. configurable: true
  50963. });
  50964. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50965. /**
  50966. * Gets if `setParticles()` computes the particle colors or not.
  50967. * Default value : true. The SPS is faster when it's set to false.
  50968. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50969. */
  50970. get: function () {
  50971. return this._computeParticleColor;
  50972. },
  50973. /**
  50974. * Tells to `setParticles()` to compute the particle colors or not.
  50975. * Default value : true. The SPS is faster when it's set to false.
  50976. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50977. */
  50978. set: function (val) {
  50979. this._computeParticleColor = val;
  50980. },
  50981. enumerable: true,
  50982. configurable: true
  50983. });
  50984. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50985. /**
  50986. * Gets if `setParticles()` computes the particle textures or not.
  50987. * Default value : true. The SPS is faster when it's set to false.
  50988. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50989. */
  50990. get: function () {
  50991. return this._computeParticleTexture;
  50992. },
  50993. set: function (val) {
  50994. this._computeParticleTexture = val;
  50995. },
  50996. enumerable: true,
  50997. configurable: true
  50998. });
  50999. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  51000. /**
  51001. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  51002. * Default value : false. The SPS is faster when it's set to false.
  51003. * Note : the particle custom vertex positions aren't stored values.
  51004. */
  51005. get: function () {
  51006. return this._computeParticleVertex;
  51007. },
  51008. /**
  51009. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  51010. * Default value : false. The SPS is faster when it's set to false.
  51011. * Note : the particle custom vertex positions aren't stored values.
  51012. */
  51013. set: function (val) {
  51014. this._computeParticleVertex = val;
  51015. },
  51016. enumerable: true,
  51017. configurable: true
  51018. });
  51019. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  51020. /**
  51021. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  51022. */
  51023. get: function () {
  51024. return this._computeBoundingBox;
  51025. },
  51026. /**
  51027. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  51028. */
  51029. set: function (val) {
  51030. this._computeBoundingBox = val;
  51031. },
  51032. enumerable: true,
  51033. configurable: true
  51034. });
  51035. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  51036. /**
  51037. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  51038. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  51039. * Default : `true`
  51040. */
  51041. get: function () {
  51042. return this._depthSortParticles;
  51043. },
  51044. /**
  51045. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  51046. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  51047. * Default : `true`
  51048. */
  51049. set: function (val) {
  51050. this._depthSortParticles = val;
  51051. },
  51052. enumerable: true,
  51053. configurable: true
  51054. });
  51055. // =======================================================================
  51056. // Particle behavior logic
  51057. // these following methods may be overwritten by the user to fit his needs
  51058. /**
  51059. * This function does nothing. It may be overwritten to set all the particle first values.
  51060. * The SPS doesn't call this function, you may have to call it by your own.
  51061. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  51062. */
  51063. SolidParticleSystem.prototype.initParticles = function () {
  51064. };
  51065. /**
  51066. * This function does nothing. It may be overwritten to recycle a particle.
  51067. * The SPS doesn't call this function, you may have to call it by your own.
  51068. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  51069. * @param particle The particle to recycle
  51070. * @returns the recycled particle
  51071. */
  51072. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  51073. return particle;
  51074. };
  51075. /**
  51076. * Updates a particle : this function should be overwritten by the user.
  51077. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  51078. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  51079. * @example : just set a particle position or velocity and recycle conditions
  51080. * @param particle The particle to update
  51081. * @returns the updated particle
  51082. */
  51083. SolidParticleSystem.prototype.updateParticle = function (particle) {
  51084. return particle;
  51085. };
  51086. /**
  51087. * Updates a vertex of a particle : it can be overwritten by the user.
  51088. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  51089. * @param particle the current particle
  51090. * @param vertex the current index of the current particle
  51091. * @param pt the index of the current vertex in the particle shape
  51092. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  51093. * @example : just set a vertex particle position
  51094. * @returns the updated vertex
  51095. */
  51096. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  51097. return vertex;
  51098. };
  51099. /**
  51100. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  51101. * This does nothing and may be overwritten by the user.
  51102. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  51103. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  51104. * @param update the boolean update value actually passed to setParticles()
  51105. */
  51106. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  51107. };
  51108. /**
  51109. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  51110. * This will be passed three parameters.
  51111. * This does nothing and may be overwritten by the user.
  51112. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  51113. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  51114. * @param update the boolean update value actually passed to setParticles()
  51115. */
  51116. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  51117. };
  51118. return SolidParticleSystem;
  51119. }());
  51120. BABYLON.SolidParticleSystem = SolidParticleSystem;
  51121. })(BABYLON || (BABYLON = {}));
  51122. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  51123. var BABYLON;
  51124. (function (BABYLON) {
  51125. var ShaderMaterial = /** @class */ (function (_super) {
  51126. __extends(ShaderMaterial, _super);
  51127. function ShaderMaterial(name, scene, shaderPath, options) {
  51128. var _this = _super.call(this, name, scene) || this;
  51129. _this._textures = {};
  51130. _this._textureArrays = {};
  51131. _this._floats = {};
  51132. _this._ints = {};
  51133. _this._floatsArrays = {};
  51134. _this._colors3 = {};
  51135. _this._colors3Arrays = {};
  51136. _this._colors4 = {};
  51137. _this._vectors2 = {};
  51138. _this._vectors3 = {};
  51139. _this._vectors4 = {};
  51140. _this._matrices = {};
  51141. _this._matrices3x3 = {};
  51142. _this._matrices2x2 = {};
  51143. _this._vectors2Arrays = {};
  51144. _this._vectors3Arrays = {};
  51145. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  51146. _this._shaderPath = shaderPath;
  51147. options.needAlphaBlending = options.needAlphaBlending || false;
  51148. options.needAlphaTesting = options.needAlphaTesting || false;
  51149. options.attributes = options.attributes || ["position", "normal", "uv"];
  51150. options.uniforms = options.uniforms || ["worldViewProjection"];
  51151. options.uniformBuffers = options.uniformBuffers || [];
  51152. options.samplers = options.samplers || [];
  51153. options.defines = options.defines || [];
  51154. _this._options = options;
  51155. return _this;
  51156. }
  51157. ShaderMaterial.prototype.getClassName = function () {
  51158. return "ShaderMaterial";
  51159. };
  51160. ShaderMaterial.prototype.needAlphaBlending = function () {
  51161. return this._options.needAlphaBlending;
  51162. };
  51163. ShaderMaterial.prototype.needAlphaTesting = function () {
  51164. return this._options.needAlphaTesting;
  51165. };
  51166. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  51167. if (this._options.uniforms.indexOf(uniformName) === -1) {
  51168. this._options.uniforms.push(uniformName);
  51169. }
  51170. };
  51171. ShaderMaterial.prototype.setTexture = function (name, texture) {
  51172. if (this._options.samplers.indexOf(name) === -1) {
  51173. this._options.samplers.push(name);
  51174. }
  51175. this._textures[name] = texture;
  51176. return this;
  51177. };
  51178. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  51179. if (this._options.samplers.indexOf(name) === -1) {
  51180. this._options.samplers.push(name);
  51181. }
  51182. this._checkUniform(name);
  51183. this._textureArrays[name] = textures;
  51184. return this;
  51185. };
  51186. ShaderMaterial.prototype.setFloat = function (name, value) {
  51187. this._checkUniform(name);
  51188. this._floats[name] = value;
  51189. return this;
  51190. };
  51191. ShaderMaterial.prototype.setInt = function (name, value) {
  51192. this._checkUniform(name);
  51193. this._ints[name] = value;
  51194. return this;
  51195. };
  51196. ShaderMaterial.prototype.setFloats = function (name, value) {
  51197. this._checkUniform(name);
  51198. this._floatsArrays[name] = value;
  51199. return this;
  51200. };
  51201. ShaderMaterial.prototype.setColor3 = function (name, value) {
  51202. this._checkUniform(name);
  51203. this._colors3[name] = value;
  51204. return this;
  51205. };
  51206. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  51207. this._checkUniform(name);
  51208. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  51209. color.toArray(arr, arr.length);
  51210. return arr;
  51211. }, []);
  51212. return this;
  51213. };
  51214. ShaderMaterial.prototype.setColor4 = function (name, value) {
  51215. this._checkUniform(name);
  51216. this._colors4[name] = value;
  51217. return this;
  51218. };
  51219. ShaderMaterial.prototype.setVector2 = function (name, value) {
  51220. this._checkUniform(name);
  51221. this._vectors2[name] = value;
  51222. return this;
  51223. };
  51224. ShaderMaterial.prototype.setVector3 = function (name, value) {
  51225. this._checkUniform(name);
  51226. this._vectors3[name] = value;
  51227. return this;
  51228. };
  51229. ShaderMaterial.prototype.setVector4 = function (name, value) {
  51230. this._checkUniform(name);
  51231. this._vectors4[name] = value;
  51232. return this;
  51233. };
  51234. ShaderMaterial.prototype.setMatrix = function (name, value) {
  51235. this._checkUniform(name);
  51236. this._matrices[name] = value;
  51237. return this;
  51238. };
  51239. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  51240. this._checkUniform(name);
  51241. this._matrices3x3[name] = value;
  51242. return this;
  51243. };
  51244. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  51245. this._checkUniform(name);
  51246. this._matrices2x2[name] = value;
  51247. return this;
  51248. };
  51249. ShaderMaterial.prototype.setArray2 = function (name, value) {
  51250. this._checkUniform(name);
  51251. this._vectors2Arrays[name] = value;
  51252. return this;
  51253. };
  51254. ShaderMaterial.prototype.setArray3 = function (name, value) {
  51255. this._checkUniform(name);
  51256. this._vectors3Arrays[name] = value;
  51257. return this;
  51258. };
  51259. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  51260. if (!mesh) {
  51261. return true;
  51262. }
  51263. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  51264. return false;
  51265. }
  51266. return false;
  51267. };
  51268. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  51269. var scene = this.getScene();
  51270. var engine = scene.getEngine();
  51271. if (!this.checkReadyOnEveryCall) {
  51272. if (this._renderId === scene.getRenderId()) {
  51273. if (this._checkCache(scene, mesh, useInstances)) {
  51274. return true;
  51275. }
  51276. }
  51277. }
  51278. // Instances
  51279. var defines = [];
  51280. var attribs = [];
  51281. var fallbacks = new BABYLON.EffectFallbacks();
  51282. if (useInstances) {
  51283. defines.push("#define INSTANCES");
  51284. }
  51285. for (var index = 0; index < this._options.defines.length; index++) {
  51286. defines.push(this._options.defines[index]);
  51287. }
  51288. for (var index = 0; index < this._options.attributes.length; index++) {
  51289. attribs.push(this._options.attributes[index]);
  51290. }
  51291. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  51292. attribs.push(BABYLON.VertexBuffer.ColorKind);
  51293. defines.push("#define VERTEXCOLOR");
  51294. }
  51295. // Bones
  51296. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  51297. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51298. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51299. if (mesh.numBoneInfluencers > 4) {
  51300. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51301. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51302. }
  51303. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51304. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51305. fallbacks.addCPUSkinningFallback(0, mesh);
  51306. if (this._options.uniforms.indexOf("mBones") === -1) {
  51307. this._options.uniforms.push("mBones");
  51308. }
  51309. }
  51310. else {
  51311. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51312. }
  51313. // Textures
  51314. for (var name in this._textures) {
  51315. if (!this._textures[name].isReady()) {
  51316. return false;
  51317. }
  51318. }
  51319. // Alpha test
  51320. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  51321. defines.push("#define ALPHATEST");
  51322. }
  51323. var previousEffect = this._effect;
  51324. var join = defines.join("\n");
  51325. this._effect = engine.createEffect(this._shaderPath, {
  51326. attributes: attribs,
  51327. uniformsNames: this._options.uniforms,
  51328. uniformBuffersNames: this._options.uniformBuffers,
  51329. samplers: this._options.samplers,
  51330. defines: join,
  51331. fallbacks: fallbacks,
  51332. onCompiled: this.onCompiled,
  51333. onError: this.onError
  51334. }, engine);
  51335. if (!this._effect.isReady()) {
  51336. return false;
  51337. }
  51338. if (previousEffect !== this._effect) {
  51339. scene.resetCachedMaterial();
  51340. }
  51341. this._renderId = scene.getRenderId();
  51342. return true;
  51343. };
  51344. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  51345. var scene = this.getScene();
  51346. if (!this._effect) {
  51347. return;
  51348. }
  51349. if (this._options.uniforms.indexOf("world") !== -1) {
  51350. this._effect.setMatrix("world", world);
  51351. }
  51352. if (this._options.uniforms.indexOf("worldView") !== -1) {
  51353. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  51354. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  51355. }
  51356. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  51357. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  51358. }
  51359. };
  51360. ShaderMaterial.prototype.bind = function (world, mesh) {
  51361. // Std values
  51362. this.bindOnlyWorldMatrix(world);
  51363. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  51364. if (this._options.uniforms.indexOf("view") !== -1) {
  51365. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  51366. }
  51367. if (this._options.uniforms.indexOf("projection") !== -1) {
  51368. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  51369. }
  51370. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  51371. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  51372. }
  51373. // Bones
  51374. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  51375. var name;
  51376. // Texture
  51377. for (name in this._textures) {
  51378. this._effect.setTexture(name, this._textures[name]);
  51379. }
  51380. // Texture arrays
  51381. for (name in this._textureArrays) {
  51382. this._effect.setTextureArray(name, this._textureArrays[name]);
  51383. }
  51384. // Int
  51385. for (name in this._ints) {
  51386. this._effect.setInt(name, this._ints[name]);
  51387. }
  51388. // Float
  51389. for (name in this._floats) {
  51390. this._effect.setFloat(name, this._floats[name]);
  51391. }
  51392. // Floats
  51393. for (name in this._floatsArrays) {
  51394. this._effect.setArray(name, this._floatsArrays[name]);
  51395. }
  51396. // Color3
  51397. for (name in this._colors3) {
  51398. this._effect.setColor3(name, this._colors3[name]);
  51399. }
  51400. for (name in this._colors3Arrays) {
  51401. this._effect.setArray3(name, this._colors3Arrays[name]);
  51402. }
  51403. // Color4
  51404. for (name in this._colors4) {
  51405. var color = this._colors4[name];
  51406. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  51407. }
  51408. // Vector2
  51409. for (name in this._vectors2) {
  51410. this._effect.setVector2(name, this._vectors2[name]);
  51411. }
  51412. // Vector3
  51413. for (name in this._vectors3) {
  51414. this._effect.setVector3(name, this._vectors3[name]);
  51415. }
  51416. // Vector4
  51417. for (name in this._vectors4) {
  51418. this._effect.setVector4(name, this._vectors4[name]);
  51419. }
  51420. // Matrix
  51421. for (name in this._matrices) {
  51422. this._effect.setMatrix(name, this._matrices[name]);
  51423. }
  51424. // Matrix 3x3
  51425. for (name in this._matrices3x3) {
  51426. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  51427. }
  51428. // Matrix 2x2
  51429. for (name in this._matrices2x2) {
  51430. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  51431. }
  51432. // Vector2Array
  51433. for (name in this._vectors2Arrays) {
  51434. this._effect.setArray2(name, this._vectors2Arrays[name]);
  51435. }
  51436. // Vector3Array
  51437. for (name in this._vectors3Arrays) {
  51438. this._effect.setArray3(name, this._vectors3Arrays[name]);
  51439. }
  51440. }
  51441. this._afterBind(mesh);
  51442. };
  51443. ShaderMaterial.prototype.getActiveTextures = function () {
  51444. var activeTextures = _super.prototype.getActiveTextures.call(this);
  51445. for (var name in this._textures) {
  51446. activeTextures.push(this._textures[name]);
  51447. }
  51448. for (var name in this._textureArrays) {
  51449. var array = this._textureArrays[name];
  51450. for (var index = 0; index < array.length; index++) {
  51451. activeTextures.push(array[index]);
  51452. }
  51453. }
  51454. return activeTextures;
  51455. };
  51456. ShaderMaterial.prototype.hasTexture = function (texture) {
  51457. if (_super.prototype.hasTexture.call(this, texture)) {
  51458. return true;
  51459. }
  51460. for (var name in this._textures) {
  51461. if (this._textures[name] === texture) {
  51462. return true;
  51463. }
  51464. }
  51465. for (var name in this._textureArrays) {
  51466. var array = this._textureArrays[name];
  51467. for (var index = 0; index < array.length; index++) {
  51468. if (array[index] === texture) {
  51469. return true;
  51470. }
  51471. }
  51472. }
  51473. return false;
  51474. };
  51475. ShaderMaterial.prototype.clone = function (name) {
  51476. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  51477. return newShaderMaterial;
  51478. };
  51479. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  51480. if (forceDisposeTextures) {
  51481. var name;
  51482. for (name in this._textures) {
  51483. this._textures[name].dispose();
  51484. }
  51485. for (name in this._textureArrays) {
  51486. var array = this._textureArrays[name];
  51487. for (var index = 0; index < array.length; index++) {
  51488. array[index].dispose();
  51489. }
  51490. }
  51491. }
  51492. this._textures = {};
  51493. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  51494. };
  51495. ShaderMaterial.prototype.serialize = function () {
  51496. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51497. serializationObject.customType = "BABYLON.ShaderMaterial";
  51498. serializationObject.options = this._options;
  51499. serializationObject.shaderPath = this._shaderPath;
  51500. var name;
  51501. // Texture
  51502. serializationObject.textures = {};
  51503. for (name in this._textures) {
  51504. serializationObject.textures[name] = this._textures[name].serialize();
  51505. }
  51506. // Texture arrays
  51507. serializationObject.textureArrays = {};
  51508. for (name in this._textureArrays) {
  51509. serializationObject.textureArrays[name] = [];
  51510. var array = this._textureArrays[name];
  51511. for (var index = 0; index < array.length; index++) {
  51512. serializationObject.textureArrays[name].push(array[index].serialize());
  51513. }
  51514. }
  51515. // Float
  51516. serializationObject.floats = {};
  51517. for (name in this._floats) {
  51518. serializationObject.floats[name] = this._floats[name];
  51519. }
  51520. // Float s
  51521. serializationObject.FloatArrays = {};
  51522. for (name in this._floatsArrays) {
  51523. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  51524. }
  51525. // Color3
  51526. serializationObject.colors3 = {};
  51527. for (name in this._colors3) {
  51528. serializationObject.colors3[name] = this._colors3[name].asArray();
  51529. }
  51530. // Color3 array
  51531. serializationObject.colors3Arrays = {};
  51532. for (name in this._colors3Arrays) {
  51533. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  51534. }
  51535. // Color4
  51536. serializationObject.colors4 = {};
  51537. for (name in this._colors4) {
  51538. serializationObject.colors4[name] = this._colors4[name].asArray();
  51539. }
  51540. // Vector2
  51541. serializationObject.vectors2 = {};
  51542. for (name in this._vectors2) {
  51543. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  51544. }
  51545. // Vector3
  51546. serializationObject.vectors3 = {};
  51547. for (name in this._vectors3) {
  51548. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  51549. }
  51550. // Vector4
  51551. serializationObject.vectors4 = {};
  51552. for (name in this._vectors4) {
  51553. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  51554. }
  51555. // Matrix
  51556. serializationObject.matrices = {};
  51557. for (name in this._matrices) {
  51558. serializationObject.matrices[name] = this._matrices[name].asArray();
  51559. }
  51560. // Matrix 3x3
  51561. serializationObject.matrices3x3 = {};
  51562. for (name in this._matrices3x3) {
  51563. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  51564. }
  51565. // Matrix 2x2
  51566. serializationObject.matrices2x2 = {};
  51567. for (name in this._matrices2x2) {
  51568. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  51569. }
  51570. // Vector2Array
  51571. serializationObject.vectors2Arrays = {};
  51572. for (name in this._vectors2Arrays) {
  51573. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  51574. }
  51575. // Vector3Array
  51576. serializationObject.vectors3Arrays = {};
  51577. for (name in this._vectors3Arrays) {
  51578. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  51579. }
  51580. return serializationObject;
  51581. };
  51582. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  51583. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  51584. var name;
  51585. // Texture
  51586. for (name in source.textures) {
  51587. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  51588. }
  51589. // Texture arrays
  51590. for (name in source.textureArrays) {
  51591. var array = source.textureArrays[name];
  51592. var textureArray = new Array();
  51593. for (var index = 0; index < array.length; index++) {
  51594. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  51595. }
  51596. material.setTextureArray(name, textureArray);
  51597. }
  51598. // Float
  51599. for (name in source.floats) {
  51600. material.setFloat(name, source.floats[name]);
  51601. }
  51602. // Float s
  51603. for (name in source.floatsArrays) {
  51604. material.setFloats(name, source.floatsArrays[name]);
  51605. }
  51606. // Color3
  51607. for (name in source.colors3) {
  51608. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  51609. }
  51610. // Color3 arrays
  51611. for (name in source.colors3Arrays) {
  51612. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  51613. if (i % 3 === 0) {
  51614. arr.push([num]);
  51615. }
  51616. else {
  51617. arr[arr.length - 1].push(num);
  51618. }
  51619. return arr;
  51620. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  51621. material.setColor3Array(name, colors);
  51622. }
  51623. // Color4
  51624. for (name in source.colors4) {
  51625. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  51626. }
  51627. // Vector2
  51628. for (name in source.vectors2) {
  51629. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  51630. }
  51631. // Vector3
  51632. for (name in source.vectors3) {
  51633. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  51634. }
  51635. // Vector4
  51636. for (name in source.vectors4) {
  51637. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  51638. }
  51639. // Matrix
  51640. for (name in source.matrices) {
  51641. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  51642. }
  51643. // Matrix 3x3
  51644. for (name in source.matrices3x3) {
  51645. material.setMatrix3x3(name, source.matrices3x3[name]);
  51646. }
  51647. // Matrix 2x2
  51648. for (name in source.matrices2x2) {
  51649. material.setMatrix2x2(name, source.matrices2x2[name]);
  51650. }
  51651. // Vector2Array
  51652. for (name in source.vectors2Arrays) {
  51653. material.setArray2(name, source.vectors2Arrays[name]);
  51654. }
  51655. // Vector3Array
  51656. for (name in source.vectors3Arrays) {
  51657. material.setArray3(name, source.vectors3Arrays[name]);
  51658. }
  51659. return material;
  51660. };
  51661. return ShaderMaterial;
  51662. }(BABYLON.Material));
  51663. BABYLON.ShaderMaterial = ShaderMaterial;
  51664. })(BABYLON || (BABYLON = {}));
  51665. //# sourceMappingURL=babylon.shaderMaterial.js.map
  51666. var BABYLON;
  51667. (function (BABYLON) {
  51668. var GroundMesh = /** @class */ (function (_super) {
  51669. __extends(GroundMesh, _super);
  51670. function GroundMesh(name, scene) {
  51671. var _this = _super.call(this, name, scene) || this;
  51672. _this.generateOctree = false;
  51673. return _this;
  51674. }
  51675. GroundMesh.prototype.getClassName = function () {
  51676. return "GroundMesh";
  51677. };
  51678. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  51679. get: function () {
  51680. return Math.min(this._subdivisionsX, this._subdivisionsY);
  51681. },
  51682. enumerable: true,
  51683. configurable: true
  51684. });
  51685. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  51686. get: function () {
  51687. return this._subdivisionsX;
  51688. },
  51689. enumerable: true,
  51690. configurable: true
  51691. });
  51692. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  51693. get: function () {
  51694. return this._subdivisionsY;
  51695. },
  51696. enumerable: true,
  51697. configurable: true
  51698. });
  51699. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  51700. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  51701. this._subdivisionsX = chunksCount;
  51702. this._subdivisionsY = chunksCount;
  51703. this.subdivide(chunksCount);
  51704. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  51705. };
  51706. /**
  51707. * Returns a height (y) value in the Worl system :
  51708. * the ground altitude at the coordinates (x, z) expressed in the World system.
  51709. * Returns the ground y position if (x, z) are outside the ground surface.
  51710. */
  51711. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  51712. var world = this.getWorldMatrix();
  51713. var invMat = BABYLON.Tmp.Matrix[5];
  51714. world.invertToRef(invMat);
  51715. var tmpVect = BABYLON.Tmp.Vector3[8];
  51716. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  51717. x = tmpVect.x;
  51718. z = tmpVect.z;
  51719. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51720. return this.position.y;
  51721. }
  51722. if (!this._heightQuads || this._heightQuads.length == 0) {
  51723. this._initHeightQuads();
  51724. this._computeHeightQuads();
  51725. }
  51726. var facet = this._getFacetAt(x, z);
  51727. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  51728. // return y in the World system
  51729. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  51730. return tmpVect.y;
  51731. };
  51732. /**
  51733. * Returns a normalized vector (Vector3) orthogonal to the ground
  51734. * at the ground coordinates (x, z) expressed in the World system.
  51735. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  51736. */
  51737. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  51738. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  51739. this.getNormalAtCoordinatesToRef(x, z, normal);
  51740. return normal;
  51741. };
  51742. /**
  51743. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  51744. * at the ground coordinates (x, z) expressed in the World system.
  51745. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  51746. * Returns the GroundMesh.
  51747. */
  51748. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  51749. var world = this.getWorldMatrix();
  51750. var tmpMat = BABYLON.Tmp.Matrix[5];
  51751. world.invertToRef(tmpMat);
  51752. var tmpVect = BABYLON.Tmp.Vector3[8];
  51753. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  51754. x = tmpVect.x;
  51755. z = tmpVect.z;
  51756. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51757. return this;
  51758. }
  51759. if (!this._heightQuads || this._heightQuads.length == 0) {
  51760. this._initHeightQuads();
  51761. this._computeHeightQuads();
  51762. }
  51763. var facet = this._getFacetAt(x, z);
  51764. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  51765. return this;
  51766. };
  51767. /**
  51768. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  51769. * if the ground has been updated.
  51770. * This can be used in the render loop.
  51771. * Returns the GroundMesh.
  51772. */
  51773. GroundMesh.prototype.updateCoordinateHeights = function () {
  51774. if (!this._heightQuads || this._heightQuads.length == 0) {
  51775. this._initHeightQuads();
  51776. }
  51777. this._computeHeightQuads();
  51778. return this;
  51779. };
  51780. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  51781. GroundMesh.prototype._getFacetAt = function (x, z) {
  51782. // retrieve col and row from x, z coordinates in the ground local system
  51783. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  51784. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  51785. var quad = this._heightQuads[row * this._subdivisionsX + col];
  51786. var facet;
  51787. if (z < quad.slope.x * x + quad.slope.y) {
  51788. facet = quad.facet1;
  51789. }
  51790. else {
  51791. facet = quad.facet2;
  51792. }
  51793. return facet;
  51794. };
  51795. // Creates and populates the heightMap array with "facet" elements :
  51796. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  51797. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51798. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51799. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51800. // Returns the GroundMesh.
  51801. GroundMesh.prototype._initHeightQuads = function () {
  51802. var subdivisionsX = this._subdivisionsX;
  51803. var subdivisionsY = this._subdivisionsY;
  51804. this._heightQuads = new Array();
  51805. for (var row = 0; row < subdivisionsY; row++) {
  51806. for (var col = 0; col < subdivisionsX; col++) {
  51807. 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) };
  51808. this._heightQuads[row * subdivisionsX + col] = quad;
  51809. }
  51810. }
  51811. return this;
  51812. };
  51813. // Compute each quad element values and update the the heightMap array :
  51814. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51815. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51816. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51817. // Returns the GroundMesh.
  51818. GroundMesh.prototype._computeHeightQuads = function () {
  51819. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51820. if (!positions) {
  51821. return this;
  51822. }
  51823. var v1 = BABYLON.Tmp.Vector3[3];
  51824. var v2 = BABYLON.Tmp.Vector3[2];
  51825. var v3 = BABYLON.Tmp.Vector3[1];
  51826. var v4 = BABYLON.Tmp.Vector3[0];
  51827. var v1v2 = BABYLON.Tmp.Vector3[4];
  51828. var v1v3 = BABYLON.Tmp.Vector3[5];
  51829. var v1v4 = BABYLON.Tmp.Vector3[6];
  51830. var norm1 = BABYLON.Tmp.Vector3[7];
  51831. var norm2 = BABYLON.Tmp.Vector3[8];
  51832. var i = 0;
  51833. var j = 0;
  51834. var k = 0;
  51835. var cd = 0; // 2D slope coefficient : z = cd * x + h
  51836. var h = 0;
  51837. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  51838. var d2 = 0;
  51839. var subdivisionsX = this._subdivisionsX;
  51840. var subdivisionsY = this._subdivisionsY;
  51841. for (var row = 0; row < subdivisionsY; row++) {
  51842. for (var col = 0; col < subdivisionsX; col++) {
  51843. i = col * 3;
  51844. j = row * (subdivisionsX + 1) * 3;
  51845. k = (row + 1) * (subdivisionsX + 1) * 3;
  51846. v1.x = positions[j + i];
  51847. v1.y = positions[j + i + 1];
  51848. v1.z = positions[j + i + 2];
  51849. v2.x = positions[j + i + 3];
  51850. v2.y = positions[j + i + 4];
  51851. v2.z = positions[j + i + 5];
  51852. v3.x = positions[k + i];
  51853. v3.y = positions[k + i + 1];
  51854. v3.z = positions[k + i + 2];
  51855. v4.x = positions[k + i + 3];
  51856. v4.y = positions[k + i + 4];
  51857. v4.z = positions[k + i + 5];
  51858. // 2D slope V1V4
  51859. cd = (v4.z - v1.z) / (v4.x - v1.x);
  51860. h = v1.z - cd * v1.x; // v1 belongs to the slope
  51861. // facet equations :
  51862. // we compute each facet normal vector
  51863. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  51864. // we compute the value d by applying the equation to v1 which belongs to the plane
  51865. // then we store the facet equation in a Vector4
  51866. v2.subtractToRef(v1, v1v2);
  51867. v3.subtractToRef(v1, v1v3);
  51868. v4.subtractToRef(v1, v1v4);
  51869. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  51870. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  51871. norm1.normalize();
  51872. norm2.normalize();
  51873. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  51874. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  51875. var quad = this._heightQuads[row * subdivisionsX + col];
  51876. quad.slope.copyFromFloats(cd, h);
  51877. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  51878. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  51879. }
  51880. }
  51881. return this;
  51882. };
  51883. GroundMesh.prototype.serialize = function (serializationObject) {
  51884. _super.prototype.serialize.call(this, serializationObject);
  51885. serializationObject.subdivisionsX = this._subdivisionsX;
  51886. serializationObject.subdivisionsY = this._subdivisionsY;
  51887. serializationObject.minX = this._minX;
  51888. serializationObject.maxX = this._maxX;
  51889. serializationObject.minZ = this._minZ;
  51890. serializationObject.maxZ = this._maxZ;
  51891. serializationObject.width = this._width;
  51892. serializationObject.height = this._height;
  51893. };
  51894. GroundMesh.Parse = function (parsedMesh, scene) {
  51895. var result = new GroundMesh(parsedMesh.name, scene);
  51896. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  51897. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  51898. result._minX = parsedMesh.minX;
  51899. result._maxX = parsedMesh.maxX;
  51900. result._minZ = parsedMesh.minZ;
  51901. result._maxZ = parsedMesh.maxZ;
  51902. result._width = parsedMesh.width;
  51903. result._height = parsedMesh.height;
  51904. return result;
  51905. };
  51906. return GroundMesh;
  51907. }(BABYLON.Mesh));
  51908. BABYLON.GroundMesh = GroundMesh;
  51909. })(BABYLON || (BABYLON = {}));
  51910. //# sourceMappingURL=babylon.groundMesh.js.map
  51911. var BABYLON;
  51912. (function (BABYLON) {
  51913. /**
  51914. * Creates an instance based on a source mesh.
  51915. */
  51916. var InstancedMesh = /** @class */ (function (_super) {
  51917. __extends(InstancedMesh, _super);
  51918. function InstancedMesh(name, source) {
  51919. var _this = _super.call(this, name, source.getScene()) || this;
  51920. source.instances.push(_this);
  51921. _this._sourceMesh = source;
  51922. _this.position.copyFrom(source.position);
  51923. _this.rotation.copyFrom(source.rotation);
  51924. _this.scaling.copyFrom(source.scaling);
  51925. if (source.rotationQuaternion) {
  51926. _this.rotationQuaternion = source.rotationQuaternion.clone();
  51927. }
  51928. _this.infiniteDistance = source.infiniteDistance;
  51929. _this.setPivotMatrix(source.getPivotMatrix());
  51930. _this.refreshBoundingInfo();
  51931. _this._syncSubMeshes();
  51932. return _this;
  51933. }
  51934. /**
  51935. * Returns the string "InstancedMesh".
  51936. */
  51937. InstancedMesh.prototype.getClassName = function () {
  51938. return "InstancedMesh";
  51939. };
  51940. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  51941. // Methods
  51942. get: function () {
  51943. return this._sourceMesh.receiveShadows;
  51944. },
  51945. enumerable: true,
  51946. configurable: true
  51947. });
  51948. Object.defineProperty(InstancedMesh.prototype, "material", {
  51949. get: function () {
  51950. return this._sourceMesh.material;
  51951. },
  51952. enumerable: true,
  51953. configurable: true
  51954. });
  51955. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  51956. get: function () {
  51957. return this._sourceMesh.visibility;
  51958. },
  51959. enumerable: true,
  51960. configurable: true
  51961. });
  51962. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  51963. get: function () {
  51964. return this._sourceMesh.skeleton;
  51965. },
  51966. enumerable: true,
  51967. configurable: true
  51968. });
  51969. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  51970. get: function () {
  51971. return this._sourceMesh.renderingGroupId;
  51972. },
  51973. enumerable: true,
  51974. configurable: true
  51975. });
  51976. /**
  51977. * Returns the total number of vertices (integer).
  51978. */
  51979. InstancedMesh.prototype.getTotalVertices = function () {
  51980. return this._sourceMesh.getTotalVertices();
  51981. };
  51982. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  51983. get: function () {
  51984. return this._sourceMesh;
  51985. },
  51986. enumerable: true,
  51987. configurable: true
  51988. });
  51989. /**
  51990. * Is this node ready to be used/rendered
  51991. * @return {boolean} is it ready
  51992. */
  51993. InstancedMesh.prototype.isReady = function () {
  51994. return this._sourceMesh.isReady(true);
  51995. };
  51996. /**
  51997. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  51998. */
  51999. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  52000. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  52001. };
  52002. /**
  52003. * Sets the vertex data of the mesh geometry for the requested `kind`.
  52004. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  52005. * The `data` are either a numeric array either a Float32Array.
  52006. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  52007. * 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).
  52008. * Note that a new underlying VertexBuffer object is created each call.
  52009. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  52010. *
  52011. * Possible `kind` values :
  52012. * - BABYLON.VertexBuffer.PositionKind
  52013. * - BABYLON.VertexBuffer.UVKind
  52014. * - BABYLON.VertexBuffer.UV2Kind
  52015. * - BABYLON.VertexBuffer.UV3Kind
  52016. * - BABYLON.VertexBuffer.UV4Kind
  52017. * - BABYLON.VertexBuffer.UV5Kind
  52018. * - BABYLON.VertexBuffer.UV6Kind
  52019. * - BABYLON.VertexBuffer.ColorKind
  52020. * - BABYLON.VertexBuffer.MatricesIndicesKind
  52021. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  52022. * - BABYLON.VertexBuffer.MatricesWeightsKind
  52023. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  52024. *
  52025. * Returns the Mesh.
  52026. */
  52027. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  52028. if (this.sourceMesh) {
  52029. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  52030. }
  52031. return this.sourceMesh;
  52032. };
  52033. /**
  52034. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  52035. * If the mesh has no geometry, it is simply returned as it is.
  52036. * The `data` are either a numeric array either a Float32Array.
  52037. * No new underlying VertexBuffer object is created.
  52038. * 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.
  52039. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  52040. *
  52041. * Possible `kind` values :
  52042. * - BABYLON.VertexBuffer.PositionKind
  52043. * - BABYLON.VertexBuffer.UVKind
  52044. * - BABYLON.VertexBuffer.UV2Kind
  52045. * - BABYLON.VertexBuffer.UV3Kind
  52046. * - BABYLON.VertexBuffer.UV4Kind
  52047. * - BABYLON.VertexBuffer.UV5Kind
  52048. * - BABYLON.VertexBuffer.UV6Kind
  52049. * - BABYLON.VertexBuffer.ColorKind
  52050. * - BABYLON.VertexBuffer.MatricesIndicesKind
  52051. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  52052. * - BABYLON.VertexBuffer.MatricesWeightsKind
  52053. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  52054. *
  52055. * Returns the Mesh.
  52056. */
  52057. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  52058. if (this.sourceMesh) {
  52059. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  52060. }
  52061. return this.sourceMesh;
  52062. };
  52063. /**
  52064. * Sets the mesh indices.
  52065. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  52066. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  52067. * This method creates a new index buffer each call.
  52068. * Returns the Mesh.
  52069. */
  52070. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  52071. if (totalVertices === void 0) { totalVertices = null; }
  52072. if (this.sourceMesh) {
  52073. this.sourceMesh.setIndices(indices, totalVertices);
  52074. }
  52075. return this.sourceMesh;
  52076. };
  52077. /**
  52078. * Boolean : True if the mesh owns the requested kind of data.
  52079. */
  52080. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  52081. return this._sourceMesh.isVerticesDataPresent(kind);
  52082. };
  52083. /**
  52084. * Returns an array of indices (IndicesArray).
  52085. */
  52086. InstancedMesh.prototype.getIndices = function () {
  52087. return this._sourceMesh.getIndices();
  52088. };
  52089. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  52090. get: function () {
  52091. return this._sourceMesh._positions;
  52092. },
  52093. enumerable: true,
  52094. configurable: true
  52095. });
  52096. /**
  52097. * Sets a new updated BoundingInfo to the mesh.
  52098. * Returns the mesh.
  52099. */
  52100. InstancedMesh.prototype.refreshBoundingInfo = function () {
  52101. var meshBB = this._sourceMesh.getBoundingInfo();
  52102. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  52103. this._updateBoundingInfo();
  52104. return this;
  52105. };
  52106. InstancedMesh.prototype._preActivate = function () {
  52107. if (this._currentLOD) {
  52108. this._currentLOD._preActivate();
  52109. }
  52110. return this;
  52111. };
  52112. InstancedMesh.prototype._activate = function (renderId) {
  52113. if (this._currentLOD) {
  52114. this._currentLOD._registerInstanceForRenderId(this, renderId);
  52115. }
  52116. return this;
  52117. };
  52118. /**
  52119. * Returns the current associated LOD AbstractMesh.
  52120. */
  52121. InstancedMesh.prototype.getLOD = function (camera) {
  52122. if (!camera) {
  52123. return this;
  52124. }
  52125. var boundingInfo = this.getBoundingInfo();
  52126. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  52127. if (this._currentLOD === this.sourceMesh) {
  52128. return this;
  52129. }
  52130. return this._currentLOD;
  52131. };
  52132. InstancedMesh.prototype._syncSubMeshes = function () {
  52133. this.releaseSubMeshes();
  52134. if (this._sourceMesh.subMeshes) {
  52135. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  52136. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  52137. }
  52138. }
  52139. return this;
  52140. };
  52141. InstancedMesh.prototype._generatePointsArray = function () {
  52142. return this._sourceMesh._generatePointsArray();
  52143. };
  52144. /**
  52145. * Creates a new InstancedMesh from the current mesh.
  52146. * - name (string) : the cloned mesh name
  52147. * - newParent (optional Node) : the optional Node to parent the clone to.
  52148. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  52149. *
  52150. * Returns the clone.
  52151. */
  52152. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  52153. var result = this._sourceMesh.createInstance(name);
  52154. // Deep copy
  52155. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  52156. // Bounding info
  52157. this.refreshBoundingInfo();
  52158. // Parent
  52159. if (newParent) {
  52160. result.parent = newParent;
  52161. }
  52162. if (!doNotCloneChildren) {
  52163. // Children
  52164. for (var index = 0; index < this.getScene().meshes.length; index++) {
  52165. var mesh = this.getScene().meshes[index];
  52166. if (mesh.parent === this) {
  52167. mesh.clone(mesh.name, result);
  52168. }
  52169. }
  52170. }
  52171. result.computeWorldMatrix(true);
  52172. return result;
  52173. };
  52174. /**
  52175. * Disposes the InstancedMesh.
  52176. * Returns nothing.
  52177. */
  52178. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  52179. // Remove from mesh
  52180. var index = this._sourceMesh.instances.indexOf(this);
  52181. this._sourceMesh.instances.splice(index, 1);
  52182. _super.prototype.dispose.call(this, doNotRecurse);
  52183. };
  52184. return InstancedMesh;
  52185. }(BABYLON.AbstractMesh));
  52186. BABYLON.InstancedMesh = InstancedMesh;
  52187. })(BABYLON || (BABYLON = {}));
  52188. //# sourceMappingURL=babylon.instancedMesh.js.map
  52189. var BABYLON;
  52190. (function (BABYLON) {
  52191. var LinesMesh = /** @class */ (function (_super) {
  52192. __extends(LinesMesh, _super);
  52193. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  52194. if (scene === void 0) { scene = null; }
  52195. if (parent === void 0) { parent = null; }
  52196. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  52197. _this.useVertexColor = useVertexColor;
  52198. _this.useVertexAlpha = useVertexAlpha;
  52199. _this.color = new BABYLON.Color3(1, 1, 1);
  52200. _this.alpha = 1;
  52201. if (source) {
  52202. _this.color = source.color.clone();
  52203. _this.alpha = source.alpha;
  52204. _this.useVertexColor = source.useVertexColor;
  52205. _this.useVertexAlpha = source.useVertexAlpha;
  52206. }
  52207. _this._intersectionThreshold = 0.1;
  52208. var defines = [];
  52209. var options = {
  52210. attributes: [BABYLON.VertexBuffer.PositionKind],
  52211. uniforms: ["world", "viewProjection"],
  52212. needAlphaBlending: true,
  52213. defines: defines
  52214. };
  52215. if (useVertexAlpha === false) {
  52216. options.needAlphaBlending = false;
  52217. }
  52218. if (!useVertexColor) {
  52219. options.uniforms.push("color");
  52220. }
  52221. else {
  52222. options.defines.push("#define VERTEXCOLOR");
  52223. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  52224. }
  52225. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  52226. return _this;
  52227. }
  52228. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  52229. /**
  52230. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  52231. * This margin is expressed in world space coordinates, so its value may vary.
  52232. * Default value is 0.1
  52233. * @returns the intersection Threshold value.
  52234. */
  52235. get: function () {
  52236. return this._intersectionThreshold;
  52237. },
  52238. /**
  52239. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  52240. * This margin is expressed in world space coordinates, so its value may vary.
  52241. * @param value the new threshold to apply
  52242. */
  52243. set: function (value) {
  52244. if (this._intersectionThreshold === value) {
  52245. return;
  52246. }
  52247. this._intersectionThreshold = value;
  52248. if (this.geometry) {
  52249. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  52250. }
  52251. },
  52252. enumerable: true,
  52253. configurable: true
  52254. });
  52255. /**
  52256. * Returns the string "LineMesh"
  52257. */
  52258. LinesMesh.prototype.getClassName = function () {
  52259. return "LinesMesh";
  52260. };
  52261. Object.defineProperty(LinesMesh.prototype, "material", {
  52262. get: function () {
  52263. return this._colorShader;
  52264. },
  52265. set: function (value) {
  52266. // Do nothing
  52267. },
  52268. enumerable: true,
  52269. configurable: true
  52270. });
  52271. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  52272. get: function () {
  52273. return false;
  52274. },
  52275. enumerable: true,
  52276. configurable: true
  52277. });
  52278. LinesMesh.prototype.createInstance = function (name) {
  52279. throw new Error("LinesMeshes do not support createInstance.");
  52280. };
  52281. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  52282. if (!this._geometry) {
  52283. return this;
  52284. }
  52285. // VBOs
  52286. this._geometry._bind(this._colorShader.getEffect());
  52287. // Color
  52288. if (!this.useVertexColor) {
  52289. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  52290. }
  52291. return this;
  52292. };
  52293. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  52294. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  52295. return this;
  52296. }
  52297. var engine = this.getScene().getEngine();
  52298. // Draw order
  52299. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  52300. return this;
  52301. };
  52302. LinesMesh.prototype.dispose = function (doNotRecurse) {
  52303. this._colorShader.dispose();
  52304. _super.prototype.dispose.call(this, doNotRecurse);
  52305. };
  52306. /**
  52307. * Returns a new LineMesh object cloned from the current one.
  52308. */
  52309. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  52310. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  52311. };
  52312. return LinesMesh;
  52313. }(BABYLON.Mesh));
  52314. BABYLON.LinesMesh = LinesMesh;
  52315. })(BABYLON || (BABYLON = {}));
  52316. //# sourceMappingURL=babylon.linesMesh.js.map
  52317. var BABYLON;
  52318. (function (BABYLON) {
  52319. var MeshBuilder = /** @class */ (function () {
  52320. function MeshBuilder() {
  52321. }
  52322. MeshBuilder.updateSideOrientation = function (orientation) {
  52323. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  52324. return BABYLON.Mesh.DOUBLESIDE;
  52325. }
  52326. if (orientation === undefined || orientation === null) {
  52327. return BABYLON.Mesh.FRONTSIDE;
  52328. }
  52329. return orientation;
  52330. };
  52331. /**
  52332. * Creates a box mesh.
  52333. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  52334. * The parameter `size` sets the size (float) of each box side (default 1).
  52335. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  52336. * 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).
  52337. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  52338. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52339. * 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).
  52340. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52341. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52342. */
  52343. MeshBuilder.CreateBox = function (name, options, scene) {
  52344. if (scene === void 0) { scene = null; }
  52345. var box = new BABYLON.Mesh(name, scene);
  52346. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52347. box._originalBuilderSideOrientation = options.sideOrientation;
  52348. var vertexData = BABYLON.VertexData.CreateBox(options);
  52349. vertexData.applyToMesh(box, options.updatable);
  52350. return box;
  52351. };
  52352. /**
  52353. * Creates a sphere mesh.
  52354. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  52355. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  52356. * 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`).
  52357. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  52358. * 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
  52359. * 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).
  52360. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52361. * 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).
  52362. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52363. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52364. */
  52365. MeshBuilder.CreateSphere = function (name, options, scene) {
  52366. var sphere = new BABYLON.Mesh(name, scene);
  52367. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52368. sphere._originalBuilderSideOrientation = options.sideOrientation;
  52369. var vertexData = BABYLON.VertexData.CreateSphere(options);
  52370. vertexData.applyToMesh(sphere, options.updatable);
  52371. return sphere;
  52372. };
  52373. /**
  52374. * Creates a plane polygonal mesh. By default, this is a disc.
  52375. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  52376. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  52377. * 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.
  52378. * 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
  52379. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52380. * 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).
  52381. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52382. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52383. */
  52384. MeshBuilder.CreateDisc = function (name, options, scene) {
  52385. if (scene === void 0) { scene = null; }
  52386. var disc = new BABYLON.Mesh(name, scene);
  52387. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52388. disc._originalBuilderSideOrientation = options.sideOrientation;
  52389. var vertexData = BABYLON.VertexData.CreateDisc(options);
  52390. vertexData.applyToMesh(disc, options.updatable);
  52391. return disc;
  52392. };
  52393. /**
  52394. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  52395. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  52396. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  52397. * 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`).
  52398. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  52399. * 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.
  52400. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52401. * 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).
  52402. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52404. */
  52405. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  52406. var sphere = new BABYLON.Mesh(name, scene);
  52407. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52408. sphere._originalBuilderSideOrientation = options.sideOrientation;
  52409. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  52410. vertexData.applyToMesh(sphere, options.updatable);
  52411. return sphere;
  52412. };
  52413. ;
  52414. /**
  52415. * Creates a ribbon mesh.
  52416. * 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.
  52417. *
  52418. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  52419. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  52420. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  52421. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  52422. * 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.
  52423. * 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.
  52424. * 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
  52425. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52426. * 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).
  52427. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52428. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52429. * 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.
  52430. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  52431. * 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
  52432. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  52433. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  52434. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52435. */
  52436. MeshBuilder.CreateRibbon = function (name, options, scene) {
  52437. if (scene === void 0) { scene = null; }
  52438. var pathArray = options.pathArray;
  52439. var closeArray = options.closeArray;
  52440. var closePath = options.closePath;
  52441. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52442. var instance = options.instance;
  52443. var updatable = options.updatable;
  52444. if (instance) {
  52445. // positionFunction : ribbon case
  52446. // only pathArray and sideOrientation parameters are taken into account for positions update
  52447. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  52448. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  52449. var positionFunction = function (positions) {
  52450. var minlg = pathArray[0].length;
  52451. var i = 0;
  52452. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  52453. for (var si = 1; si <= ns; si++) {
  52454. for (var p = 0; p < pathArray.length; p++) {
  52455. var path = pathArray[p];
  52456. var l = path.length;
  52457. minlg = (minlg < l) ? minlg : l;
  52458. var j = 0;
  52459. while (j < minlg) {
  52460. positions[i] = path[j].x;
  52461. positions[i + 1] = path[j].y;
  52462. positions[i + 2] = path[j].z;
  52463. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  52464. BABYLON.Tmp.Vector3[0].x = path[j].x;
  52465. }
  52466. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  52467. BABYLON.Tmp.Vector3[1].x = path[j].x;
  52468. }
  52469. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  52470. BABYLON.Tmp.Vector3[0].y = path[j].y;
  52471. }
  52472. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  52473. BABYLON.Tmp.Vector3[1].y = path[j].y;
  52474. }
  52475. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  52476. BABYLON.Tmp.Vector3[0].z = path[j].z;
  52477. }
  52478. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  52479. BABYLON.Tmp.Vector3[1].z = path[j].z;
  52480. }
  52481. j++;
  52482. i += 3;
  52483. }
  52484. if (instance._closePath) {
  52485. positions[i] = path[0].x;
  52486. positions[i + 1] = path[0].y;
  52487. positions[i + 2] = path[0].z;
  52488. i += 3;
  52489. }
  52490. }
  52491. }
  52492. };
  52493. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52494. positionFunction(positions);
  52495. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  52496. instance._boundingInfo.update(instance._worldMatrix);
  52497. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52498. if (options.colors) {
  52499. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52500. for (var c = 0; c < options.colors.length; c++) {
  52501. colors[c * 4] = options.colors[c].r;
  52502. colors[c * 4 + 1] = options.colors[c].g;
  52503. colors[c * 4 + 2] = options.colors[c].b;
  52504. colors[c * 4 + 3] = options.colors[c].a;
  52505. }
  52506. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  52507. }
  52508. if (options.uvs) {
  52509. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52510. for (var i = 0; i < options.uvs.length; i++) {
  52511. uvs[i * 2] = options.uvs[i].x;
  52512. uvs[i * 2 + 1] = options.uvs[i].y;
  52513. }
  52514. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  52515. }
  52516. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  52517. var indices = instance.getIndices();
  52518. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52519. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  52520. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  52521. if (instance._closePath) {
  52522. var indexFirst = 0;
  52523. var indexLast = 0;
  52524. for (var p = 0; p < pathArray.length; p++) {
  52525. indexFirst = instance._idx[p] * 3;
  52526. if (p + 1 < pathArray.length) {
  52527. indexLast = (instance._idx[p + 1] - 1) * 3;
  52528. }
  52529. else {
  52530. indexLast = normals.length - 3;
  52531. }
  52532. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  52533. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  52534. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  52535. normals[indexLast] = normals[indexFirst];
  52536. normals[indexLast + 1] = normals[indexFirst + 1];
  52537. normals[indexLast + 2] = normals[indexFirst + 2];
  52538. }
  52539. }
  52540. if (!(instance.areNormalsFrozen)) {
  52541. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  52542. }
  52543. }
  52544. return instance;
  52545. }
  52546. else {
  52547. var ribbon = new BABYLON.Mesh(name, scene);
  52548. ribbon._originalBuilderSideOrientation = sideOrientation;
  52549. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  52550. if (closePath) {
  52551. ribbon._idx = vertexData._idx;
  52552. }
  52553. ribbon._closePath = closePath;
  52554. ribbon._closeArray = closeArray;
  52555. vertexData.applyToMesh(ribbon, updatable);
  52556. return ribbon;
  52557. }
  52558. };
  52559. /**
  52560. * Creates a cylinder or a cone mesh.
  52561. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  52562. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  52563. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  52564. * 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.
  52565. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  52566. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  52567. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  52568. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  52569. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  52570. * 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).
  52571. * 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
  52572. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  52573. * 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
  52574. * 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.
  52575. * If `enclose` is false, a ring surface is one element.
  52576. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  52577. * 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
  52578. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52579. * 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).
  52580. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52581. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52582. */
  52583. MeshBuilder.CreateCylinder = function (name, options, scene) {
  52584. var cylinder = new BABYLON.Mesh(name, scene);
  52585. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52586. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  52587. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  52588. vertexData.applyToMesh(cylinder, options.updatable);
  52589. return cylinder;
  52590. };
  52591. /**
  52592. * Creates a torus mesh.
  52593. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  52594. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  52595. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  52596. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  52597. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52598. * 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).
  52599. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52600. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52601. */
  52602. MeshBuilder.CreateTorus = function (name, options, scene) {
  52603. var torus = new BABYLON.Mesh(name, scene);
  52604. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52605. torus._originalBuilderSideOrientation = options.sideOrientation;
  52606. var vertexData = BABYLON.VertexData.CreateTorus(options);
  52607. vertexData.applyToMesh(torus, options.updatable);
  52608. return torus;
  52609. };
  52610. /**
  52611. * Creates a torus knot mesh.
  52612. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  52613. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  52614. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  52615. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  52616. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  52617. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52618. * 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).
  52619. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52621. */
  52622. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  52623. var torusKnot = new BABYLON.Mesh(name, scene);
  52624. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52625. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  52626. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  52627. vertexData.applyToMesh(torusKnot, options.updatable);
  52628. return torusKnot;
  52629. };
  52630. /**
  52631. * Creates a line system mesh.
  52632. * A line system is a pool of many lines gathered in a single mesh.
  52633. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  52634. * 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.
  52635. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  52636. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  52637. * 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
  52638. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  52639. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  52640. * 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
  52641. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  52642. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52643. */
  52644. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  52645. var instance = options.instance;
  52646. var lines = options.lines;
  52647. var colors = options.colors;
  52648. if (instance) {
  52649. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52650. var vertexColor;
  52651. var lineColors;
  52652. if (colors) {
  52653. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52654. }
  52655. var i = 0;
  52656. var c = 0;
  52657. for (var l = 0; l < lines.length; l++) {
  52658. var points = lines[l];
  52659. for (var p = 0; p < points.length; p++) {
  52660. positions[i] = points[p].x;
  52661. positions[i + 1] = points[p].y;
  52662. positions[i + 2] = points[p].z;
  52663. if (colors && vertexColor) {
  52664. lineColors = colors[l];
  52665. vertexColor[c] = lineColors[p].r;
  52666. vertexColor[c + 1] = lineColors[p].g;
  52667. vertexColor[c + 2] = lineColors[p].b;
  52668. vertexColor[c + 3] = lineColors[p].a;
  52669. c += 4;
  52670. }
  52671. i += 3;
  52672. }
  52673. }
  52674. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52675. if (colors && vertexColor) {
  52676. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  52677. }
  52678. return instance;
  52679. }
  52680. // line system creation
  52681. var useVertexColor = (colors) ? true : false;
  52682. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  52683. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  52684. vertexData.applyToMesh(lineSystem, options.updatable);
  52685. return lineSystem;
  52686. };
  52687. /**
  52688. * Creates a line mesh.
  52689. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  52690. * 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.
  52691. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52692. * The parameter `points` is an array successive Vector3.
  52693. * 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
  52694. * The optional parameter `colors` is an array of successive Color4, one per line point.
  52695. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  52696. * When updating an instance, remember that only point positions can change, not the number of points.
  52697. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52698. */
  52699. MeshBuilder.CreateLines = function (name, options, scene) {
  52700. if (scene === void 0) { scene = null; }
  52701. var colors = (options.colors) ? [options.colors] : null;
  52702. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  52703. return lines;
  52704. };
  52705. /**
  52706. * Creates a dashed line mesh.
  52707. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  52708. * 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.
  52709. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52710. * The parameter `points` is an array successive Vector3.
  52711. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  52712. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  52713. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  52714. * 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
  52715. * When updating an instance, remember that only point positions can change, not the number of points.
  52716. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52717. */
  52718. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  52719. if (scene === void 0) { scene = null; }
  52720. var points = options.points;
  52721. var instance = options.instance;
  52722. var gapSize = options.gapSize || 1;
  52723. var dashSize = options.dashSize || 3;
  52724. if (instance) {
  52725. var positionFunction = function (positions) {
  52726. var curvect = BABYLON.Vector3.Zero();
  52727. var nbSeg = positions.length / 6;
  52728. var lg = 0;
  52729. var nb = 0;
  52730. var shft = 0;
  52731. var dashshft = 0;
  52732. var curshft = 0;
  52733. var p = 0;
  52734. var i = 0;
  52735. var j = 0;
  52736. for (i = 0; i < points.length - 1; i++) {
  52737. points[i + 1].subtractToRef(points[i], curvect);
  52738. lg += curvect.length();
  52739. }
  52740. shft = lg / nbSeg;
  52741. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  52742. for (i = 0; i < points.length - 1; i++) {
  52743. points[i + 1].subtractToRef(points[i], curvect);
  52744. nb = Math.floor(curvect.length() / shft);
  52745. curvect.normalize();
  52746. j = 0;
  52747. while (j < nb && p < positions.length) {
  52748. curshft = shft * j;
  52749. positions[p] = points[i].x + curshft * curvect.x;
  52750. positions[p + 1] = points[i].y + curshft * curvect.y;
  52751. positions[p + 2] = points[i].z + curshft * curvect.z;
  52752. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  52753. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  52754. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  52755. p += 6;
  52756. j++;
  52757. }
  52758. }
  52759. while (p < positions.length) {
  52760. positions[p] = points[i].x;
  52761. positions[p + 1] = points[i].y;
  52762. positions[p + 2] = points[i].z;
  52763. p += 3;
  52764. }
  52765. };
  52766. instance.updateMeshPositions(positionFunction, false);
  52767. return instance;
  52768. }
  52769. // dashed lines creation
  52770. var dashedLines = new BABYLON.LinesMesh(name, scene);
  52771. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  52772. vertexData.applyToMesh(dashedLines, options.updatable);
  52773. dashedLines.dashSize = dashSize;
  52774. dashedLines.gapSize = gapSize;
  52775. return dashedLines;
  52776. };
  52777. /**
  52778. * Creates an extruded shape mesh.
  52779. * 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.
  52780. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  52781. *
  52782. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52783. * 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
  52784. * extruded along the Z axis.
  52785. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52786. * 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.
  52787. * The parameter `scale` (float, default 1) is the value to scale the shape.
  52788. * 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
  52789. * 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
  52790. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52792. * 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).
  52793. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52794. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52795. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52796. */
  52797. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  52798. if (scene === void 0) { scene = null; }
  52799. var path = options.path;
  52800. var shape = options.shape;
  52801. var scale = options.scale || 1;
  52802. var rotation = options.rotation || 0;
  52803. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52804. var updatable = options.updatable;
  52805. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52806. var instance = options.instance || null;
  52807. var invertUV = options.invertUV || false;
  52808. 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);
  52809. };
  52810. /**
  52811. * Creates an custom extruded shape mesh.
  52812. * 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.
  52813. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  52814. *
  52815. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52816. * 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
  52817. * extruded along the Z axis.
  52818. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52819. * 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
  52820. * and the distance of this point from the begining of the path :
  52821. * ```javascript
  52822. * var rotationFunction = function(i, distance) {
  52823. * // do things
  52824. * return rotationValue; }
  52825. * ```
  52826. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  52827. * 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
  52828. * and the distance of this point from the begining of the path :
  52829. * ```javascript
  52830. * var scaleFunction = function(i, distance) {
  52831. * // do things
  52832. * return scaleValue;}
  52833. * ```
  52834. * It must returns a float value that will be the scale value applied to the shape on each path point.
  52835. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  52836. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  52837. * 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
  52838. * 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
  52839. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52840. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52841. * 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).
  52842. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52843. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52844. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52845. */
  52846. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  52847. var path = options.path;
  52848. var shape = options.shape;
  52849. var scaleFunction = options.scaleFunction || (function () { return 1; });
  52850. var rotationFunction = options.rotationFunction || (function () { return 0; });
  52851. var ribbonCloseArray = options.ribbonCloseArray || false;
  52852. var ribbonClosePath = options.ribbonClosePath || false;
  52853. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52854. var updatable = options.updatable;
  52855. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52856. var instance = options.instance;
  52857. var invertUV = options.invertUV || false;
  52858. 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);
  52859. };
  52860. /**
  52861. * Creates lathe mesh.
  52862. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  52863. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  52864. *
  52865. * 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
  52866. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  52867. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  52868. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  52869. * 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.
  52870. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  52871. * 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
  52872. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52873. * 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).
  52874. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52875. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52876. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52877. */
  52878. MeshBuilder.CreateLathe = function (name, options, scene) {
  52879. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  52880. var closed = (options.closed === undefined) ? true : options.closed;
  52881. var shape = options.shape;
  52882. var radius = options.radius || 1;
  52883. var tessellation = options.tessellation || 64;
  52884. var updatable = options.updatable;
  52885. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52886. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52887. var pi2 = Math.PI * 2;
  52888. var paths = new Array();
  52889. var invertUV = options.invertUV || false;
  52890. var i = 0;
  52891. var p = 0;
  52892. var step = pi2 / tessellation * arc;
  52893. var rotated;
  52894. var path = new Array();
  52895. ;
  52896. for (i = 0; i <= tessellation; i++) {
  52897. var path = [];
  52898. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  52899. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  52900. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  52901. }
  52902. for (p = 0; p < shape.length; p++) {
  52903. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  52904. path.push(rotated);
  52905. }
  52906. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  52907. 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));
  52908. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  52909. }
  52910. paths.push(path);
  52911. }
  52912. // lathe ribbon
  52913. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52914. return lathe;
  52915. };
  52916. /**
  52917. * Creates a plane mesh.
  52918. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52919. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  52920. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  52921. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  52922. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52923. * 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).
  52924. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52925. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52926. */
  52927. MeshBuilder.CreatePlane = function (name, options, scene) {
  52928. var plane = new BABYLON.Mesh(name, scene);
  52929. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52930. plane._originalBuilderSideOrientation = options.sideOrientation;
  52931. var vertexData = BABYLON.VertexData.CreatePlane(options);
  52932. vertexData.applyToMesh(plane, options.updatable);
  52933. if (options.sourcePlane) {
  52934. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  52935. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  52936. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  52937. plane.rotate(vectorProduct, product);
  52938. }
  52939. return plane;
  52940. };
  52941. /**
  52942. * Creates a ground mesh.
  52943. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52944. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  52945. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  52946. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52947. */
  52948. MeshBuilder.CreateGround = function (name, options, scene) {
  52949. var ground = new BABYLON.GroundMesh(name, scene);
  52950. ground._setReady(false);
  52951. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  52952. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  52953. ground._width = options.width || 1;
  52954. ground._height = options.height || 1;
  52955. ground._maxX = ground._width / 2;
  52956. ground._maxZ = ground._height / 2;
  52957. ground._minX = -ground._maxX;
  52958. ground._minZ = -ground._maxZ;
  52959. var vertexData = BABYLON.VertexData.CreateGround(options);
  52960. vertexData.applyToMesh(ground, options.updatable);
  52961. ground._setReady(true);
  52962. return ground;
  52963. };
  52964. /**
  52965. * Creates a tiled ground mesh.
  52966. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  52967. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  52968. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  52969. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  52970. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  52971. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  52972. * numbers of subdivisions on the ground width and height of each tile.
  52973. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52974. */
  52975. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  52976. var tiledGround = new BABYLON.Mesh(name, scene);
  52977. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  52978. vertexData.applyToMesh(tiledGround, options.updatable);
  52979. return tiledGround;
  52980. };
  52981. /**
  52982. * Creates a ground mesh from a height map.
  52983. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  52984. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  52985. * The parameter `url` sets the URL of the height map image resource.
  52986. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  52987. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  52988. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  52989. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  52990. * 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.
  52991. * 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).
  52992. * This function is passed the newly built mesh :
  52993. * ```javascript
  52994. * function(mesh) { // do things
  52995. * return; }
  52996. * ```
  52997. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52998. */
  52999. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  53000. var width = options.width || 10.0;
  53001. var height = options.height || 10.0;
  53002. var subdivisions = options.subdivisions || 1 | 0;
  53003. var minHeight = options.minHeight || 0.0;
  53004. var maxHeight = options.maxHeight || 1.0;
  53005. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  53006. var updatable = options.updatable;
  53007. var onReady = options.onReady;
  53008. var ground = new BABYLON.GroundMesh(name, scene);
  53009. ground._subdivisionsX = subdivisions;
  53010. ground._subdivisionsY = subdivisions;
  53011. ground._width = width;
  53012. ground._height = height;
  53013. ground._maxX = ground._width / 2.0;
  53014. ground._maxZ = ground._height / 2.0;
  53015. ground._minX = -ground._maxX;
  53016. ground._minZ = -ground._maxZ;
  53017. ground._setReady(false);
  53018. var onload = function (img) {
  53019. // Getting height map data
  53020. var canvas = document.createElement("canvas");
  53021. var context = canvas.getContext("2d");
  53022. if (!context) {
  53023. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  53024. }
  53025. if (scene.isDisposed) {
  53026. return;
  53027. }
  53028. var bufferWidth = img.width;
  53029. var bufferHeight = img.height;
  53030. canvas.width = bufferWidth;
  53031. canvas.height = bufferHeight;
  53032. context.drawImage(img, 0, 0);
  53033. // Create VertexData from map data
  53034. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  53035. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  53036. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  53037. width: width, height: height,
  53038. subdivisions: subdivisions,
  53039. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  53040. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  53041. });
  53042. vertexData.applyToMesh(ground, updatable);
  53043. ground._setReady(true);
  53044. //execute ready callback, if set
  53045. if (onReady) {
  53046. onReady(ground);
  53047. }
  53048. };
  53049. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  53050. return ground;
  53051. };
  53052. /**
  53053. * Creates a polygon mesh.
  53054. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  53055. * 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.
  53056. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53057. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53058. * 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).
  53059. * Remember you can only change the shape positions, not their number when updating a polygon.
  53060. */
  53061. MeshBuilder.CreatePolygon = function (name, options, scene) {
  53062. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53063. var shape = options.shape;
  53064. var holes = options.holes || [];
  53065. var depth = options.depth || 0;
  53066. var contours = [];
  53067. var hole = [];
  53068. for (var i = 0; i < shape.length; i++) {
  53069. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  53070. }
  53071. var epsilon = 0.00000001;
  53072. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  53073. contours.pop();
  53074. }
  53075. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  53076. for (var hNb = 0; hNb < holes.length; hNb++) {
  53077. hole = [];
  53078. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  53079. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  53080. }
  53081. polygonTriangulation.addHole(hole);
  53082. }
  53083. var polygon = polygonTriangulation.build(options.updatable, depth);
  53084. polygon._originalBuilderSideOrientation = options.sideOrientation;
  53085. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  53086. vertexData.applyToMesh(polygon, options.updatable);
  53087. return polygon;
  53088. };
  53089. ;
  53090. /**
  53091. * Creates an extruded polygon mesh, with depth in the Y direction.
  53092. * 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).
  53093. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53094. */
  53095. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  53096. return MeshBuilder.CreatePolygon(name, options, scene);
  53097. };
  53098. ;
  53099. /**
  53100. * Creates a tube mesh.
  53101. * 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.
  53102. *
  53103. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  53104. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  53105. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  53106. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  53107. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  53108. * 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.
  53109. * It must return a radius value (positive float) :
  53110. * ```javascript
  53111. * var radiusFunction = function(i, distance) {
  53112. * // do things
  53113. * return radius; }
  53114. * ```
  53115. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  53116. * 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
  53117. * 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
  53118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53119. * 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).
  53120. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53121. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53123. */
  53124. MeshBuilder.CreateTube = function (name, options, scene) {
  53125. var path = options.path;
  53126. var instance = options.instance;
  53127. var radius = 1.0;
  53128. if (instance) {
  53129. radius = instance.radius;
  53130. }
  53131. if (options.radius !== undefined) {
  53132. radius = options.radius;
  53133. }
  53134. ;
  53135. var tessellation = options.tessellation || 64 | 0;
  53136. var radiusFunction = options.radiusFunction || null;
  53137. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  53138. var invertUV = options.invertUV || false;
  53139. var updatable = options.updatable;
  53140. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53141. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  53142. // tube geometry
  53143. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  53144. var tangents = path3D.getTangents();
  53145. var normals = path3D.getNormals();
  53146. var distances = path3D.getDistances();
  53147. var pi2 = Math.PI * 2;
  53148. var step = pi2 / tessellation * arc;
  53149. var returnRadius = function () { return radius; };
  53150. var radiusFunctionFinal = radiusFunction || returnRadius;
  53151. var circlePath;
  53152. var rad;
  53153. var normal;
  53154. var rotated;
  53155. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  53156. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  53157. for (var i = 0; i < path.length; i++) {
  53158. rad = radiusFunctionFinal(i, distances[i]); // current radius
  53159. circlePath = Array(); // current circle array
  53160. normal = normals[i]; // current normal
  53161. for (var t = 0; t < tessellation; t++) {
  53162. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  53163. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  53164. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  53165. rotated.scaleInPlace(rad).addInPlace(path[i]);
  53166. circlePath[t] = rotated;
  53167. }
  53168. circlePaths[index] = circlePath;
  53169. index++;
  53170. }
  53171. // cap
  53172. var capPath = function (nbPoints, pathIndex) {
  53173. var pointCap = Array();
  53174. for (var i = 0; i < nbPoints; i++) {
  53175. pointCap.push(path[pathIndex]);
  53176. }
  53177. return pointCap;
  53178. };
  53179. switch (cap) {
  53180. case BABYLON.Mesh.NO_CAP:
  53181. break;
  53182. case BABYLON.Mesh.CAP_START:
  53183. circlePaths[0] = capPath(tessellation, 0);
  53184. circlePaths[1] = circlePaths[2].slice(0);
  53185. break;
  53186. case BABYLON.Mesh.CAP_END:
  53187. circlePaths[index] = circlePaths[index - 1].slice(0);
  53188. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  53189. break;
  53190. case BABYLON.Mesh.CAP_ALL:
  53191. circlePaths[0] = capPath(tessellation, 0);
  53192. circlePaths[1] = circlePaths[2].slice(0);
  53193. circlePaths[index] = circlePaths[index - 1].slice(0);
  53194. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  53195. break;
  53196. default:
  53197. break;
  53198. }
  53199. return circlePaths;
  53200. };
  53201. var path3D;
  53202. var pathArray;
  53203. if (instance) {
  53204. var arc = options.arc || instance.arc;
  53205. path3D = (instance.path3D).update(path);
  53206. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  53207. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  53208. instance.path3D = path3D;
  53209. instance.pathArray = pathArray;
  53210. instance.arc = arc;
  53211. instance.radius = radius;
  53212. return instance;
  53213. }
  53214. // tube creation
  53215. path3D = new BABYLON.Path3D(path);
  53216. var newPathArray = new Array();
  53217. cap = (cap < 0 || cap > 3) ? 0 : cap;
  53218. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  53219. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  53220. tube.pathArray = pathArray;
  53221. tube.path3D = path3D;
  53222. tube.tessellation = tessellation;
  53223. tube.cap = cap;
  53224. tube.arc = options.arc;
  53225. tube.radius = radius;
  53226. return tube;
  53227. };
  53228. /**
  53229. * Creates a polyhedron mesh.
  53230. *
  53231. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  53232. * 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
  53233. * to choose the wanted type.
  53234. * The parameter `size` (positive float, default 1) sets the polygon size.
  53235. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  53236. * 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`.
  53237. * 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
  53238. * 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)`).
  53239. * 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
  53240. * 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.
  53241. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53242. * 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).
  53243. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53244. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53245. */
  53246. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  53247. var polyhedron = new BABYLON.Mesh(name, scene);
  53248. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53249. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  53250. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  53251. vertexData.applyToMesh(polyhedron, options.updatable);
  53252. return polyhedron;
  53253. };
  53254. /**
  53255. * Creates a decal mesh.
  53256. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  53257. * 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.
  53258. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  53259. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  53260. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  53261. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  53262. */
  53263. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  53264. var indices = sourceMesh.getIndices();
  53265. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53266. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53267. var position = options.position || BABYLON.Vector3.Zero();
  53268. var normal = options.normal || BABYLON.Vector3.Up();
  53269. var size = options.size || BABYLON.Vector3.One();
  53270. var angle = options.angle || 0;
  53271. // Getting correct rotation
  53272. if (!normal) {
  53273. var target = new BABYLON.Vector3(0, 0, 1);
  53274. var camera = sourceMesh.getScene().activeCamera;
  53275. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  53276. normal = camera.globalPosition.subtract(cameraWorldTarget);
  53277. }
  53278. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  53279. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  53280. var pitch = Math.atan2(normal.y, len);
  53281. // Matrix
  53282. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  53283. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  53284. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  53285. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  53286. var vertexData = new BABYLON.VertexData();
  53287. vertexData.indices = [];
  53288. vertexData.positions = [];
  53289. vertexData.normals = [];
  53290. vertexData.uvs = [];
  53291. var currentVertexDataIndex = 0;
  53292. var extractDecalVector3 = function (indexId) {
  53293. var result = new BABYLON.PositionNormalVertex();
  53294. if (!indices || !positions || !normals) {
  53295. return result;
  53296. }
  53297. var vertexId = indices[indexId];
  53298. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  53299. // Send vector to decal local world
  53300. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  53301. // Get normal
  53302. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  53303. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  53304. return result;
  53305. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  53306. var clip = function (vertices, axis) {
  53307. if (vertices.length === 0) {
  53308. return vertices;
  53309. }
  53310. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  53311. var clipVertices = function (v0, v1) {
  53312. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  53313. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  53314. };
  53315. var result = new Array();
  53316. for (var index = 0; index < vertices.length; index += 3) {
  53317. var v1Out;
  53318. var v2Out;
  53319. var v3Out;
  53320. var total = 0;
  53321. var nV1 = null;
  53322. var nV2 = null;
  53323. var nV3 = null;
  53324. var nV4 = null;
  53325. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  53326. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  53327. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  53328. v1Out = d1 > 0;
  53329. v2Out = d2 > 0;
  53330. v3Out = d3 > 0;
  53331. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  53332. switch (total) {
  53333. case 0:
  53334. result.push(vertices[index]);
  53335. result.push(vertices[index + 1]);
  53336. result.push(vertices[index + 2]);
  53337. break;
  53338. case 1:
  53339. if (v1Out) {
  53340. nV1 = vertices[index + 1];
  53341. nV2 = vertices[index + 2];
  53342. nV3 = clipVertices(vertices[index], nV1);
  53343. nV4 = clipVertices(vertices[index], nV2);
  53344. }
  53345. if (v2Out) {
  53346. nV1 = vertices[index];
  53347. nV2 = vertices[index + 2];
  53348. nV3 = clipVertices(vertices[index + 1], nV1);
  53349. nV4 = clipVertices(vertices[index + 1], nV2);
  53350. result.push(nV3);
  53351. result.push(nV2.clone());
  53352. result.push(nV1.clone());
  53353. result.push(nV2.clone());
  53354. result.push(nV3.clone());
  53355. result.push(nV4);
  53356. break;
  53357. }
  53358. if (v3Out) {
  53359. nV1 = vertices[index];
  53360. nV2 = vertices[index + 1];
  53361. nV3 = clipVertices(vertices[index + 2], nV1);
  53362. nV4 = clipVertices(vertices[index + 2], nV2);
  53363. }
  53364. if (nV1 && nV2 && nV3 && nV4) {
  53365. result.push(nV1.clone());
  53366. result.push(nV2.clone());
  53367. result.push(nV3);
  53368. result.push(nV4);
  53369. result.push(nV3.clone());
  53370. result.push(nV2.clone());
  53371. }
  53372. break;
  53373. case 2:
  53374. if (!v1Out) {
  53375. nV1 = vertices[index].clone();
  53376. nV2 = clipVertices(nV1, vertices[index + 1]);
  53377. nV3 = clipVertices(nV1, vertices[index + 2]);
  53378. result.push(nV1);
  53379. result.push(nV2);
  53380. result.push(nV3);
  53381. }
  53382. if (!v2Out) {
  53383. nV1 = vertices[index + 1].clone();
  53384. nV2 = clipVertices(nV1, vertices[index + 2]);
  53385. nV3 = clipVertices(nV1, vertices[index]);
  53386. result.push(nV1);
  53387. result.push(nV2);
  53388. result.push(nV3);
  53389. }
  53390. if (!v3Out) {
  53391. nV1 = vertices[index + 2].clone();
  53392. nV2 = clipVertices(nV1, vertices[index]);
  53393. nV3 = clipVertices(nV1, vertices[index + 1]);
  53394. result.push(nV1);
  53395. result.push(nV2);
  53396. result.push(nV3);
  53397. }
  53398. break;
  53399. case 3:
  53400. break;
  53401. }
  53402. }
  53403. return result;
  53404. };
  53405. for (var index = 0; index < indices.length; index += 3) {
  53406. var faceVertices = new Array();
  53407. faceVertices.push(extractDecalVector3(index));
  53408. faceVertices.push(extractDecalVector3(index + 1));
  53409. faceVertices.push(extractDecalVector3(index + 2));
  53410. // Clip
  53411. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  53412. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  53413. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  53414. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  53415. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  53416. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  53417. if (faceVertices.length === 0) {
  53418. continue;
  53419. }
  53420. // Add UVs and get back to world
  53421. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  53422. var vertex = faceVertices[vIndex];
  53423. //TODO check for Int32Array | Uint32Array | Uint16Array
  53424. vertexData.indices.push(currentVertexDataIndex);
  53425. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  53426. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  53427. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  53428. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  53429. currentVertexDataIndex++;
  53430. }
  53431. }
  53432. // Return mesh
  53433. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  53434. vertexData.applyToMesh(decal);
  53435. decal.position = position.clone();
  53436. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  53437. return decal;
  53438. };
  53439. // Privates
  53440. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  53441. // extrusion geometry
  53442. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  53443. var tangents = path3D.getTangents();
  53444. var normals = path3D.getNormals();
  53445. var binormals = path3D.getBinormals();
  53446. var distances = path3D.getDistances();
  53447. var angle = 0;
  53448. var returnScale = function () { return scale !== null ? scale : 1; };
  53449. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  53450. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  53451. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  53452. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  53453. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  53454. for (var i = 0; i < curve.length; i++) {
  53455. var shapePath = new Array();
  53456. var angleStep = rotate(i, distances[i]);
  53457. var scaleRatio = scl(i, distances[i]);
  53458. for (var p = 0; p < shape.length; p++) {
  53459. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  53460. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  53461. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  53462. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  53463. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  53464. shapePath[p] = rotated;
  53465. }
  53466. shapePaths[index] = shapePath;
  53467. angle += angleStep;
  53468. index++;
  53469. }
  53470. // cap
  53471. var capPath = function (shapePath) {
  53472. var pointCap = Array();
  53473. var barycenter = BABYLON.Vector3.Zero();
  53474. var i;
  53475. for (i = 0; i < shapePath.length; i++) {
  53476. barycenter.addInPlace(shapePath[i]);
  53477. }
  53478. barycenter.scaleInPlace(1.0 / shapePath.length);
  53479. for (i = 0; i < shapePath.length; i++) {
  53480. pointCap.push(barycenter);
  53481. }
  53482. return pointCap;
  53483. };
  53484. switch (cap) {
  53485. case BABYLON.Mesh.NO_CAP:
  53486. break;
  53487. case BABYLON.Mesh.CAP_START:
  53488. shapePaths[0] = capPath(shapePaths[2]);
  53489. shapePaths[1] = shapePaths[2];
  53490. break;
  53491. case BABYLON.Mesh.CAP_END:
  53492. shapePaths[index] = shapePaths[index - 1];
  53493. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53494. break;
  53495. case BABYLON.Mesh.CAP_ALL:
  53496. shapePaths[0] = capPath(shapePaths[2]);
  53497. shapePaths[1] = shapePaths[2];
  53498. shapePaths[index] = shapePaths[index - 1];
  53499. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53500. break;
  53501. default:
  53502. break;
  53503. }
  53504. return shapePaths;
  53505. };
  53506. var path3D;
  53507. var pathArray;
  53508. if (instance) {
  53509. path3D = (instance.path3D).update(curve);
  53510. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  53511. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  53512. return instance;
  53513. }
  53514. // extruded shape creation
  53515. path3D = new BABYLON.Path3D(curve);
  53516. var newShapePaths = new Array();
  53517. cap = (cap < 0 || cap > 3) ? 0 : cap;
  53518. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  53519. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  53520. extrudedGeneric.pathArray = pathArray;
  53521. extrudedGeneric.path3D = path3D;
  53522. extrudedGeneric.cap = cap;
  53523. return extrudedGeneric;
  53524. };
  53525. return MeshBuilder;
  53526. }());
  53527. BABYLON.MeshBuilder = MeshBuilder;
  53528. })(BABYLON || (BABYLON = {}));
  53529. //# sourceMappingURL=babylon.meshBuilder.js.map
  53530. var BABYLON;
  53531. (function (BABYLON) {
  53532. var AudioEngine = /** @class */ (function () {
  53533. function AudioEngine() {
  53534. this._audioContext = null;
  53535. this._audioContextInitialized = false;
  53536. this.canUseWebAudio = false;
  53537. this.WarnedWebAudioUnsupported = false;
  53538. this.unlocked = false;
  53539. this.isMP3supported = false;
  53540. this.isOGGsupported = false;
  53541. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  53542. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  53543. this.canUseWebAudio = true;
  53544. }
  53545. var audioElem = document.createElement('audio');
  53546. try {
  53547. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  53548. this.isMP3supported = true;
  53549. }
  53550. }
  53551. catch (e) {
  53552. // protect error during capability check.
  53553. }
  53554. try {
  53555. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  53556. this.isOGGsupported = true;
  53557. }
  53558. }
  53559. catch (e) {
  53560. // protect error during capability check.
  53561. }
  53562. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  53563. this._unlockiOSaudio();
  53564. }
  53565. else {
  53566. this.unlocked = true;
  53567. }
  53568. }
  53569. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  53570. get: function () {
  53571. if (!this._audioContextInitialized) {
  53572. this._initializeAudioContext();
  53573. }
  53574. return this._audioContext;
  53575. },
  53576. enumerable: true,
  53577. configurable: true
  53578. });
  53579. AudioEngine.prototype._unlockiOSaudio = function () {
  53580. var _this = this;
  53581. var unlockaudio = function () {
  53582. if (!_this.audioContext) {
  53583. return;
  53584. }
  53585. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  53586. var source = _this.audioContext.createBufferSource();
  53587. source.buffer = buffer;
  53588. source.connect(_this.audioContext.destination);
  53589. source.start(0);
  53590. setTimeout(function () {
  53591. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  53592. _this.unlocked = true;
  53593. window.removeEventListener('touchend', unlockaudio, false);
  53594. if (_this.onAudioUnlocked) {
  53595. _this.onAudioUnlocked();
  53596. }
  53597. }
  53598. }, 0);
  53599. };
  53600. window.addEventListener('touchend', unlockaudio, false);
  53601. };
  53602. AudioEngine.prototype._initializeAudioContext = function () {
  53603. try {
  53604. if (this.canUseWebAudio) {
  53605. this._audioContext = new AudioContext();
  53606. // create a global volume gain node
  53607. this.masterGain = this._audioContext.createGain();
  53608. this.masterGain.gain.value = 1;
  53609. this.masterGain.connect(this._audioContext.destination);
  53610. this._audioContextInitialized = true;
  53611. }
  53612. }
  53613. catch (e) {
  53614. this.canUseWebAudio = false;
  53615. BABYLON.Tools.Error("Web Audio: " + e.message);
  53616. }
  53617. };
  53618. AudioEngine.prototype.dispose = function () {
  53619. if (this.canUseWebAudio && this._audioContextInitialized) {
  53620. if (this._connectedAnalyser && this._audioContext) {
  53621. this._connectedAnalyser.stopDebugCanvas();
  53622. this._connectedAnalyser.dispose();
  53623. this.masterGain.disconnect();
  53624. this.masterGain.connect(this._audioContext.destination);
  53625. this._connectedAnalyser = null;
  53626. }
  53627. this.masterGain.gain.value = 1;
  53628. }
  53629. this.WarnedWebAudioUnsupported = false;
  53630. };
  53631. AudioEngine.prototype.getGlobalVolume = function () {
  53632. if (this.canUseWebAudio && this._audioContextInitialized) {
  53633. return this.masterGain.gain.value;
  53634. }
  53635. else {
  53636. return -1;
  53637. }
  53638. };
  53639. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  53640. if (this.canUseWebAudio && this._audioContextInitialized) {
  53641. this.masterGain.gain.value = newVolume;
  53642. }
  53643. };
  53644. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  53645. if (this._connectedAnalyser) {
  53646. this._connectedAnalyser.stopDebugCanvas();
  53647. }
  53648. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  53649. this._connectedAnalyser = analyser;
  53650. this.masterGain.disconnect();
  53651. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  53652. }
  53653. };
  53654. return AudioEngine;
  53655. }());
  53656. BABYLON.AudioEngine = AudioEngine;
  53657. })(BABYLON || (BABYLON = {}));
  53658. //# sourceMappingURL=babylon.audioEngine.js.map
  53659. var BABYLON;
  53660. (function (BABYLON) {
  53661. var Sound = /** @class */ (function () {
  53662. /**
  53663. * Create a sound and attach it to a scene
  53664. * @param name Name of your sound
  53665. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  53666. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  53667. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  53668. */
  53669. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  53670. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  53671. var _this = this;
  53672. this.autoplay = false;
  53673. this.loop = false;
  53674. this.useCustomAttenuation = false;
  53675. this.spatialSound = false;
  53676. this.refDistance = 1;
  53677. this.rolloffFactor = 1;
  53678. this.maxDistance = 100;
  53679. this.distanceModel = "linear";
  53680. this._panningModel = "equalpower";
  53681. this._playbackRate = 1;
  53682. this._streaming = false;
  53683. this._startTime = 0;
  53684. this._startOffset = 0;
  53685. this._position = BABYLON.Vector3.Zero();
  53686. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  53687. this._volume = 1;
  53688. this._isReadyToPlay = false;
  53689. this.isPlaying = false;
  53690. this.isPaused = false;
  53691. this._isDirectional = false;
  53692. // Used if you'd like to create a directional sound.
  53693. // If not set, the sound will be omnidirectional
  53694. this._coneInnerAngle = 360;
  53695. this._coneOuterAngle = 360;
  53696. this._coneOuterGain = 0;
  53697. this._isOutputConnected = false;
  53698. this._urlType = "Unknown";
  53699. this.name = name;
  53700. this._scene = scene;
  53701. this._readyToPlayCallback = readyToPlayCallback;
  53702. // Default custom attenuation function is a linear attenuation
  53703. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  53704. if (currentDistance < maxDistance) {
  53705. return currentVolume * (1 - currentDistance / maxDistance);
  53706. }
  53707. else {
  53708. return 0;
  53709. }
  53710. };
  53711. if (options) {
  53712. this.autoplay = options.autoplay || false;
  53713. this.loop = options.loop || false;
  53714. // if volume === 0, we need another way to check this option
  53715. if (options.volume !== undefined) {
  53716. this._volume = options.volume;
  53717. }
  53718. this.spatialSound = options.spatialSound || false;
  53719. this.maxDistance = options.maxDistance || 100;
  53720. this.useCustomAttenuation = options.useCustomAttenuation || false;
  53721. this.rolloffFactor = options.rolloffFactor || 1;
  53722. this.refDistance = options.refDistance || 1;
  53723. this.distanceModel = options.distanceModel || "linear";
  53724. this._playbackRate = options.playbackRate || 1;
  53725. this._streaming = options.streaming || false;
  53726. }
  53727. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53728. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  53729. this._soundGain.gain.value = this._volume;
  53730. this._inputAudioNode = this._soundGain;
  53731. this._ouputAudioNode = this._soundGain;
  53732. if (this.spatialSound) {
  53733. this._createSpatialParameters();
  53734. }
  53735. this._scene.mainSoundTrack.AddSound(this);
  53736. var validParameter = true;
  53737. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  53738. if (urlOrArrayBuffer) {
  53739. if (typeof (urlOrArrayBuffer) === "string")
  53740. this._urlType = "String";
  53741. if (Array.isArray(urlOrArrayBuffer))
  53742. this._urlType = "Array";
  53743. if (urlOrArrayBuffer instanceof ArrayBuffer)
  53744. this._urlType = "ArrayBuffer";
  53745. var urls = [];
  53746. var codecSupportedFound = false;
  53747. switch (this._urlType) {
  53748. case "ArrayBuffer":
  53749. if (urlOrArrayBuffer.byteLength > 0) {
  53750. codecSupportedFound = true;
  53751. this._soundLoaded(urlOrArrayBuffer);
  53752. }
  53753. break;
  53754. case "String":
  53755. urls.push(urlOrArrayBuffer);
  53756. case "Array":
  53757. if (urls.length === 0)
  53758. urls = urlOrArrayBuffer;
  53759. // If we found a supported format, we load it immediately and stop the loop
  53760. for (var i = 0; i < urls.length; i++) {
  53761. var url = urls[i];
  53762. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  53763. codecSupportedFound = true;
  53764. }
  53765. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  53766. codecSupportedFound = true;
  53767. }
  53768. if (url.indexOf(".wav", url.length - 4) !== -1) {
  53769. codecSupportedFound = true;
  53770. }
  53771. if (url.indexOf("blob:") !== -1) {
  53772. codecSupportedFound = true;
  53773. }
  53774. if (codecSupportedFound) {
  53775. // Loading sound using XHR2
  53776. if (!this._streaming) {
  53777. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  53778. }
  53779. else {
  53780. this._htmlAudioElement = new Audio(url);
  53781. this._htmlAudioElement.controls = false;
  53782. this._htmlAudioElement.loop = this.loop;
  53783. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  53784. this._htmlAudioElement.preload = "auto";
  53785. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  53786. _this._isReadyToPlay = true;
  53787. if (_this.autoplay) {
  53788. _this.play();
  53789. }
  53790. if (_this._readyToPlayCallback) {
  53791. _this._readyToPlayCallback();
  53792. }
  53793. });
  53794. document.body.appendChild(this._htmlAudioElement);
  53795. }
  53796. break;
  53797. }
  53798. }
  53799. break;
  53800. default:
  53801. validParameter = false;
  53802. break;
  53803. }
  53804. if (!validParameter) {
  53805. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  53806. }
  53807. else {
  53808. if (!codecSupportedFound) {
  53809. this._isReadyToPlay = true;
  53810. // Simulating a ready to play event to avoid breaking code path
  53811. if (this._readyToPlayCallback) {
  53812. window.setTimeout(function () {
  53813. if (_this._readyToPlayCallback) {
  53814. _this._readyToPlayCallback();
  53815. }
  53816. }, 1000);
  53817. }
  53818. }
  53819. }
  53820. }
  53821. }
  53822. else {
  53823. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  53824. this._scene.mainSoundTrack.AddSound(this);
  53825. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  53826. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  53827. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  53828. }
  53829. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  53830. if (this._readyToPlayCallback) {
  53831. window.setTimeout(function () {
  53832. if (_this._readyToPlayCallback) {
  53833. _this._readyToPlayCallback();
  53834. }
  53835. }, 1000);
  53836. }
  53837. }
  53838. }
  53839. Sound.prototype.dispose = function () {
  53840. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  53841. if (this.isPlaying) {
  53842. this.stop();
  53843. }
  53844. this._isReadyToPlay = false;
  53845. if (this.soundTrackId === -1) {
  53846. this._scene.mainSoundTrack.RemoveSound(this);
  53847. }
  53848. else {
  53849. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  53850. }
  53851. if (this._soundGain) {
  53852. this._soundGain.disconnect();
  53853. this._soundGain = null;
  53854. }
  53855. if (this._soundPanner) {
  53856. this._soundPanner.disconnect();
  53857. this._soundPanner = null;
  53858. }
  53859. if (this._soundSource) {
  53860. this._soundSource.disconnect();
  53861. this._soundSource = null;
  53862. }
  53863. this._audioBuffer = null;
  53864. if (this._htmlAudioElement) {
  53865. this._htmlAudioElement.pause();
  53866. this._htmlAudioElement.src = "";
  53867. document.body.removeChild(this._htmlAudioElement);
  53868. }
  53869. if (this._connectedMesh && this._registerFunc) {
  53870. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53871. this._connectedMesh = null;
  53872. }
  53873. }
  53874. };
  53875. Sound.prototype.isReady = function () {
  53876. return this._isReadyToPlay;
  53877. };
  53878. Sound.prototype._soundLoaded = function (audioData) {
  53879. var _this = this;
  53880. if (!BABYLON.Engine.audioEngine.audioContext) {
  53881. return;
  53882. }
  53883. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  53884. _this._audioBuffer = buffer;
  53885. _this._isReadyToPlay = true;
  53886. if (_this.autoplay) {
  53887. _this.play();
  53888. }
  53889. if (_this._readyToPlayCallback) {
  53890. _this._readyToPlayCallback();
  53891. }
  53892. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  53893. };
  53894. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  53895. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53896. this._audioBuffer = audioBuffer;
  53897. this._isReadyToPlay = true;
  53898. }
  53899. };
  53900. Sound.prototype.updateOptions = function (options) {
  53901. if (options) {
  53902. this.loop = options.loop || this.loop;
  53903. this.maxDistance = options.maxDistance || this.maxDistance;
  53904. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  53905. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  53906. this.refDistance = options.refDistance || this.refDistance;
  53907. this.distanceModel = options.distanceModel || this.distanceModel;
  53908. this._playbackRate = options.playbackRate || this._playbackRate;
  53909. this._updateSpatialParameters();
  53910. if (this.isPlaying) {
  53911. if (this._streaming) {
  53912. this._htmlAudioElement.playbackRate = this._playbackRate;
  53913. }
  53914. else {
  53915. if (this._soundSource) {
  53916. this._soundSource.playbackRate.value = this._playbackRate;
  53917. }
  53918. }
  53919. }
  53920. }
  53921. };
  53922. Sound.prototype._createSpatialParameters = function () {
  53923. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53924. if (this._scene.headphone) {
  53925. this._panningModel = "HRTF";
  53926. }
  53927. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  53928. this._updateSpatialParameters();
  53929. this._soundPanner.connect(this._ouputAudioNode);
  53930. this._inputAudioNode = this._soundPanner;
  53931. }
  53932. };
  53933. Sound.prototype._updateSpatialParameters = function () {
  53934. if (this.spatialSound && this._soundPanner) {
  53935. if (this.useCustomAttenuation) {
  53936. // Tricks to disable in a way embedded Web Audio attenuation
  53937. this._soundPanner.distanceModel = "linear";
  53938. this._soundPanner.maxDistance = Number.MAX_VALUE;
  53939. this._soundPanner.refDistance = 1;
  53940. this._soundPanner.rolloffFactor = 1;
  53941. this._soundPanner.panningModel = this._panningModel;
  53942. }
  53943. else {
  53944. this._soundPanner.distanceModel = this.distanceModel;
  53945. this._soundPanner.maxDistance = this.maxDistance;
  53946. this._soundPanner.refDistance = this.refDistance;
  53947. this._soundPanner.rolloffFactor = this.rolloffFactor;
  53948. this._soundPanner.panningModel = this._panningModel;
  53949. }
  53950. }
  53951. };
  53952. Sound.prototype.switchPanningModelToHRTF = function () {
  53953. this._panningModel = "HRTF";
  53954. this._switchPanningModel();
  53955. };
  53956. Sound.prototype.switchPanningModelToEqualPower = function () {
  53957. this._panningModel = "equalpower";
  53958. this._switchPanningModel();
  53959. };
  53960. Sound.prototype._switchPanningModel = function () {
  53961. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53962. this._soundPanner.panningModel = this._panningModel;
  53963. }
  53964. };
  53965. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  53966. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53967. if (this._isOutputConnected) {
  53968. this._ouputAudioNode.disconnect();
  53969. }
  53970. this._ouputAudioNode.connect(soundTrackAudioNode);
  53971. this._isOutputConnected = true;
  53972. }
  53973. };
  53974. /**
  53975. * Transform this sound into a directional source
  53976. * @param coneInnerAngle Size of the inner cone in degree
  53977. * @param coneOuterAngle Size of the outer cone in degree
  53978. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  53979. */
  53980. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  53981. if (coneOuterAngle < coneInnerAngle) {
  53982. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  53983. return;
  53984. }
  53985. this._coneInnerAngle = coneInnerAngle;
  53986. this._coneOuterAngle = coneOuterAngle;
  53987. this._coneOuterGain = coneOuterGain;
  53988. this._isDirectional = true;
  53989. if (this.isPlaying && this.loop) {
  53990. this.stop();
  53991. this.play();
  53992. }
  53993. };
  53994. Sound.prototype.setPosition = function (newPosition) {
  53995. this._position = newPosition;
  53996. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53997. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53998. }
  53999. };
  54000. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  54001. this._localDirection = newLocalDirection;
  54002. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  54003. this._updateDirection();
  54004. }
  54005. };
  54006. Sound.prototype._updateDirection = function () {
  54007. if (!this._connectedMesh || !this._soundPanner) {
  54008. return;
  54009. }
  54010. var mat = this._connectedMesh.getWorldMatrix();
  54011. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  54012. direction.normalize();
  54013. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  54014. };
  54015. Sound.prototype.updateDistanceFromListener = function () {
  54016. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  54017. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  54018. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  54019. }
  54020. };
  54021. Sound.prototype.setAttenuationFunction = function (callback) {
  54022. this._customAttenuationFunction = callback;
  54023. };
  54024. /**
  54025. * Play the sound
  54026. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  54027. * @param offset (optional) Start the sound setting it at a specific time
  54028. */
  54029. Sound.prototype.play = function (time, offset) {
  54030. var _this = this;
  54031. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  54032. try {
  54033. if (this._startOffset < 0) {
  54034. time = -this._startOffset;
  54035. this._startOffset = 0;
  54036. }
  54037. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  54038. if (!this._soundSource || !this._streamingSource) {
  54039. if (this.spatialSound && this._soundPanner) {
  54040. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  54041. if (this._isDirectional) {
  54042. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  54043. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  54044. this._soundPanner.coneOuterGain = this._coneOuterGain;
  54045. if (this._connectedMesh) {
  54046. this._updateDirection();
  54047. }
  54048. else {
  54049. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  54050. }
  54051. }
  54052. }
  54053. }
  54054. if (this._streaming) {
  54055. if (!this._streamingSource) {
  54056. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  54057. this._htmlAudioElement.onended = function () { _this._onended(); };
  54058. this._htmlAudioElement.playbackRate = this._playbackRate;
  54059. }
  54060. this._streamingSource.disconnect();
  54061. this._streamingSource.connect(this._inputAudioNode);
  54062. this._htmlAudioElement.play();
  54063. }
  54064. else {
  54065. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  54066. this._soundSource.buffer = this._audioBuffer;
  54067. this._soundSource.connect(this._inputAudioNode);
  54068. this._soundSource.loop = this.loop;
  54069. this._soundSource.playbackRate.value = this._playbackRate;
  54070. this._soundSource.onended = function () { _this._onended(); };
  54071. if (this._soundSource.buffer) {
  54072. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  54073. }
  54074. }
  54075. this._startTime = startTime;
  54076. this.isPlaying = true;
  54077. this.isPaused = false;
  54078. }
  54079. catch (ex) {
  54080. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  54081. }
  54082. }
  54083. };
  54084. Sound.prototype._onended = function () {
  54085. this.isPlaying = false;
  54086. if (this.onended) {
  54087. this.onended();
  54088. }
  54089. };
  54090. /**
  54091. * Stop the sound
  54092. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  54093. */
  54094. Sound.prototype.stop = function (time) {
  54095. if (this.isPlaying) {
  54096. if (this._streaming) {
  54097. this._htmlAudioElement.pause();
  54098. // Test needed for Firefox or it will generate an Invalid State Error
  54099. if (this._htmlAudioElement.currentTime > 0) {
  54100. this._htmlAudioElement.currentTime = 0;
  54101. }
  54102. }
  54103. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  54104. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  54105. this._soundSource.stop(stopTime);
  54106. this._soundSource.onended = function () { };
  54107. if (!this.isPaused) {
  54108. this._startOffset = 0;
  54109. }
  54110. }
  54111. this.isPlaying = false;
  54112. }
  54113. };
  54114. Sound.prototype.pause = function () {
  54115. if (this.isPlaying) {
  54116. this.isPaused = true;
  54117. if (this._streaming) {
  54118. this._htmlAudioElement.pause();
  54119. }
  54120. else if (BABYLON.Engine.audioEngine.audioContext) {
  54121. this.stop(0);
  54122. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  54123. }
  54124. }
  54125. };
  54126. Sound.prototype.setVolume = function (newVolume, time) {
  54127. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  54128. if (time && BABYLON.Engine.audioEngine.audioContext) {
  54129. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  54130. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  54131. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  54132. }
  54133. else {
  54134. this._soundGain.gain.value = newVolume;
  54135. }
  54136. }
  54137. this._volume = newVolume;
  54138. };
  54139. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  54140. this._playbackRate = newPlaybackRate;
  54141. if (this.isPlaying) {
  54142. if (this._streaming) {
  54143. this._htmlAudioElement.playbackRate = this._playbackRate;
  54144. }
  54145. else if (this._soundSource) {
  54146. this._soundSource.playbackRate.value = this._playbackRate;
  54147. }
  54148. }
  54149. };
  54150. Sound.prototype.getVolume = function () {
  54151. return this._volume;
  54152. };
  54153. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  54154. var _this = this;
  54155. if (this._connectedMesh && this._registerFunc) {
  54156. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  54157. this._registerFunc = null;
  54158. }
  54159. this._connectedMesh = meshToConnectTo;
  54160. if (!this.spatialSound) {
  54161. this.spatialSound = true;
  54162. this._createSpatialParameters();
  54163. if (this.isPlaying && this.loop) {
  54164. this.stop();
  54165. this.play();
  54166. }
  54167. }
  54168. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  54169. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  54170. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  54171. };
  54172. Sound.prototype.detachFromMesh = function () {
  54173. if (this._connectedMesh && this._registerFunc) {
  54174. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  54175. this._registerFunc = null;
  54176. this._connectedMesh = null;
  54177. }
  54178. };
  54179. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  54180. if (!node.getBoundingInfo) {
  54181. return;
  54182. }
  54183. var mesh = node;
  54184. var boundingInfo = mesh.getBoundingInfo();
  54185. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  54186. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  54187. this._updateDirection();
  54188. }
  54189. };
  54190. Sound.prototype.clone = function () {
  54191. var _this = this;
  54192. if (!this._streaming) {
  54193. var setBufferAndRun = function () {
  54194. if (_this._isReadyToPlay) {
  54195. clonedSound._audioBuffer = _this.getAudioBuffer();
  54196. clonedSound._isReadyToPlay = true;
  54197. if (clonedSound.autoplay) {
  54198. clonedSound.play();
  54199. }
  54200. }
  54201. else {
  54202. window.setTimeout(setBufferAndRun, 300);
  54203. }
  54204. };
  54205. var currentOptions = {
  54206. autoplay: this.autoplay, loop: this.loop,
  54207. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  54208. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  54209. refDistance: this.refDistance, distanceModel: this.distanceModel
  54210. };
  54211. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  54212. if (this.useCustomAttenuation) {
  54213. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  54214. }
  54215. clonedSound.setPosition(this._position);
  54216. clonedSound.setPlaybackRate(this._playbackRate);
  54217. setBufferAndRun();
  54218. return clonedSound;
  54219. }
  54220. else {
  54221. return null;
  54222. }
  54223. };
  54224. Sound.prototype.getAudioBuffer = function () {
  54225. return this._audioBuffer;
  54226. };
  54227. Sound.prototype.serialize = function () {
  54228. var serializationObject = {
  54229. name: this.name,
  54230. url: this.name,
  54231. autoplay: this.autoplay,
  54232. loop: this.loop,
  54233. volume: this._volume,
  54234. spatialSound: this.spatialSound,
  54235. maxDistance: this.maxDistance,
  54236. rolloffFactor: this.rolloffFactor,
  54237. refDistance: this.refDistance,
  54238. distanceModel: this.distanceModel,
  54239. playbackRate: this._playbackRate,
  54240. panningModel: this._panningModel,
  54241. soundTrackId: this.soundTrackId
  54242. };
  54243. if (this.spatialSound) {
  54244. if (this._connectedMesh)
  54245. serializationObject.connectedMeshId = this._connectedMesh.id;
  54246. serializationObject.position = this._position.asArray();
  54247. serializationObject.refDistance = this.refDistance;
  54248. serializationObject.distanceModel = this.distanceModel;
  54249. serializationObject.isDirectional = this._isDirectional;
  54250. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  54251. serializationObject.coneInnerAngle = this._coneInnerAngle;
  54252. serializationObject.coneOuterAngle = this._coneOuterAngle;
  54253. serializationObject.coneOuterGain = this._coneOuterGain;
  54254. }
  54255. return serializationObject;
  54256. };
  54257. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  54258. var soundName = parsedSound.name;
  54259. var soundUrl;
  54260. if (parsedSound.url) {
  54261. soundUrl = rootUrl + parsedSound.url;
  54262. }
  54263. else {
  54264. soundUrl = rootUrl + soundName;
  54265. }
  54266. var options = {
  54267. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  54268. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  54269. rolloffFactor: parsedSound.rolloffFactor,
  54270. refDistance: parsedSound.refDistance,
  54271. distanceModel: parsedSound.distanceModel,
  54272. playbackRate: parsedSound.playbackRate
  54273. };
  54274. var newSound;
  54275. if (!sourceSound) {
  54276. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  54277. scene._addPendingData(newSound);
  54278. }
  54279. else {
  54280. var setBufferAndRun = function () {
  54281. if (sourceSound._isReadyToPlay) {
  54282. newSound._audioBuffer = sourceSound.getAudioBuffer();
  54283. newSound._isReadyToPlay = true;
  54284. if (newSound.autoplay) {
  54285. newSound.play();
  54286. }
  54287. }
  54288. else {
  54289. window.setTimeout(setBufferAndRun, 300);
  54290. }
  54291. };
  54292. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  54293. setBufferAndRun();
  54294. }
  54295. if (parsedSound.position) {
  54296. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  54297. newSound.setPosition(soundPosition);
  54298. }
  54299. if (parsedSound.isDirectional) {
  54300. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  54301. if (parsedSound.localDirectionToMesh) {
  54302. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  54303. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  54304. }
  54305. }
  54306. if (parsedSound.connectedMeshId) {
  54307. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  54308. if (connectedMesh) {
  54309. newSound.attachToMesh(connectedMesh);
  54310. }
  54311. }
  54312. return newSound;
  54313. };
  54314. return Sound;
  54315. }());
  54316. BABYLON.Sound = Sound;
  54317. })(BABYLON || (BABYLON = {}));
  54318. //# sourceMappingURL=babylon.sound.js.map
  54319. var BABYLON;
  54320. (function (BABYLON) {
  54321. var SoundTrack = /** @class */ (function () {
  54322. function SoundTrack(scene, options) {
  54323. this.id = -1;
  54324. this._isMainTrack = false;
  54325. this._isInitialized = false;
  54326. this._scene = scene;
  54327. this.soundCollection = new Array();
  54328. this._options = options;
  54329. if (!this._isMainTrack) {
  54330. this._scene.soundTracks.push(this);
  54331. this.id = this._scene.soundTracks.length - 1;
  54332. }
  54333. }
  54334. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  54335. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  54336. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  54337. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  54338. if (this._options) {
  54339. if (this._options.volume) {
  54340. this._outputAudioNode.gain.value = this._options.volume;
  54341. }
  54342. if (this._options.mainTrack) {
  54343. this._isMainTrack = this._options.mainTrack;
  54344. }
  54345. }
  54346. this._isInitialized = true;
  54347. }
  54348. };
  54349. SoundTrack.prototype.dispose = function () {
  54350. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54351. if (this._connectedAnalyser) {
  54352. this._connectedAnalyser.stopDebugCanvas();
  54353. }
  54354. while (this.soundCollection.length) {
  54355. this.soundCollection[0].dispose();
  54356. }
  54357. if (this._outputAudioNode) {
  54358. this._outputAudioNode.disconnect();
  54359. }
  54360. this._outputAudioNode = null;
  54361. }
  54362. };
  54363. SoundTrack.prototype.AddSound = function (sound) {
  54364. if (!this._isInitialized) {
  54365. this._initializeSoundTrackAudioGraph();
  54366. }
  54367. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  54368. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  54369. }
  54370. if (sound.soundTrackId) {
  54371. if (sound.soundTrackId === -1) {
  54372. this._scene.mainSoundTrack.RemoveSound(sound);
  54373. }
  54374. else {
  54375. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  54376. }
  54377. }
  54378. this.soundCollection.push(sound);
  54379. sound.soundTrackId = this.id;
  54380. };
  54381. SoundTrack.prototype.RemoveSound = function (sound) {
  54382. var index = this.soundCollection.indexOf(sound);
  54383. if (index !== -1) {
  54384. this.soundCollection.splice(index, 1);
  54385. }
  54386. };
  54387. SoundTrack.prototype.setVolume = function (newVolume) {
  54388. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  54389. this._outputAudioNode.gain.value = newVolume;
  54390. }
  54391. };
  54392. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  54393. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54394. for (var i = 0; i < this.soundCollection.length; i++) {
  54395. this.soundCollection[i].switchPanningModelToHRTF();
  54396. }
  54397. }
  54398. };
  54399. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  54400. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54401. for (var i = 0; i < this.soundCollection.length; i++) {
  54402. this.soundCollection[i].switchPanningModelToEqualPower();
  54403. }
  54404. }
  54405. };
  54406. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  54407. if (this._connectedAnalyser) {
  54408. this._connectedAnalyser.stopDebugCanvas();
  54409. }
  54410. this._connectedAnalyser = analyser;
  54411. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  54412. this._outputAudioNode.disconnect();
  54413. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  54414. }
  54415. };
  54416. return SoundTrack;
  54417. }());
  54418. BABYLON.SoundTrack = SoundTrack;
  54419. })(BABYLON || (BABYLON = {}));
  54420. //# sourceMappingURL=babylon.soundtrack.js.map
  54421. var BABYLON;
  54422. (function (BABYLON) {
  54423. var Analyser = /** @class */ (function () {
  54424. function Analyser(scene) {
  54425. this.SMOOTHING = 0.75;
  54426. this.FFT_SIZE = 512;
  54427. this.BARGRAPHAMPLITUDE = 256;
  54428. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  54429. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  54430. this._scene = scene;
  54431. this._audioEngine = BABYLON.Engine.audioEngine;
  54432. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  54433. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  54434. this._webAudioAnalyser.minDecibels = -140;
  54435. this._webAudioAnalyser.maxDecibels = 0;
  54436. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54437. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54438. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  54439. }
  54440. }
  54441. Analyser.prototype.getFrequencyBinCount = function () {
  54442. if (this._audioEngine.canUseWebAudio) {
  54443. return this._webAudioAnalyser.frequencyBinCount;
  54444. }
  54445. else {
  54446. return 0;
  54447. }
  54448. };
  54449. Analyser.prototype.getByteFrequencyData = function () {
  54450. if (this._audioEngine.canUseWebAudio) {
  54451. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54452. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54453. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  54454. }
  54455. return this._byteFreqs;
  54456. };
  54457. Analyser.prototype.getByteTimeDomainData = function () {
  54458. if (this._audioEngine.canUseWebAudio) {
  54459. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54460. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54461. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  54462. }
  54463. return this._byteTime;
  54464. };
  54465. Analyser.prototype.getFloatFrequencyData = function () {
  54466. if (this._audioEngine.canUseWebAudio) {
  54467. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54468. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54469. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  54470. }
  54471. return this._floatFreqs;
  54472. };
  54473. Analyser.prototype.drawDebugCanvas = function () {
  54474. var _this = this;
  54475. if (this._audioEngine.canUseWebAudio) {
  54476. if (!this._debugCanvas) {
  54477. this._debugCanvas = document.createElement("canvas");
  54478. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  54479. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  54480. this._debugCanvas.style.position = "absolute";
  54481. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  54482. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  54483. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  54484. document.body.appendChild(this._debugCanvas);
  54485. this._registerFunc = function () {
  54486. _this.drawDebugCanvas();
  54487. };
  54488. this._scene.registerBeforeRender(this._registerFunc);
  54489. }
  54490. if (this._registerFunc && this._debugCanvasContext) {
  54491. var workingArray = this.getByteFrequencyData();
  54492. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  54493. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  54494. // Draw the frequency domain chart.
  54495. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  54496. var value = workingArray[i];
  54497. var percent = value / this.BARGRAPHAMPLITUDE;
  54498. var height = this.DEBUGCANVASSIZE.height * percent;
  54499. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  54500. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  54501. var hue = i / this.getFrequencyBinCount() * 360;
  54502. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  54503. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  54504. }
  54505. }
  54506. }
  54507. };
  54508. Analyser.prototype.stopDebugCanvas = function () {
  54509. if (this._debugCanvas) {
  54510. if (this._registerFunc) {
  54511. this._scene.unregisterBeforeRender(this._registerFunc);
  54512. this._registerFunc = null;
  54513. }
  54514. document.body.removeChild(this._debugCanvas);
  54515. this._debugCanvas = null;
  54516. this._debugCanvasContext = null;
  54517. }
  54518. };
  54519. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  54520. if (this._audioEngine.canUseWebAudio) {
  54521. inputAudioNode.connect(this._webAudioAnalyser);
  54522. this._webAudioAnalyser.connect(outputAudioNode);
  54523. }
  54524. };
  54525. Analyser.prototype.dispose = function () {
  54526. if (this._audioEngine.canUseWebAudio) {
  54527. this._webAudioAnalyser.disconnect();
  54528. }
  54529. };
  54530. return Analyser;
  54531. }());
  54532. BABYLON.Analyser = Analyser;
  54533. })(BABYLON || (BABYLON = {}));
  54534. //# sourceMappingURL=babylon.analyser.js.map
  54535. var BABYLON;
  54536. (function (BABYLON) {
  54537. var CubeTexture = /** @class */ (function (_super) {
  54538. __extends(CubeTexture, _super);
  54539. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  54540. if (extensions === void 0) { extensions = null; }
  54541. if (noMipmap === void 0) { noMipmap = false; }
  54542. if (files === void 0) { files = null; }
  54543. if (onLoad === void 0) { onLoad = null; }
  54544. if (onError === void 0) { onError = null; }
  54545. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54546. if (prefiltered === void 0) { prefiltered = false; }
  54547. if (forcedExtension === void 0) { forcedExtension = null; }
  54548. var _this = _super.call(this, scene) || this;
  54549. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  54550. _this.name = rootUrl;
  54551. _this.url = rootUrl;
  54552. _this._noMipmap = noMipmap;
  54553. _this.hasAlpha = false;
  54554. _this._format = format;
  54555. _this._prefiltered = prefiltered;
  54556. _this.isCube = true;
  54557. _this._textureMatrix = BABYLON.Matrix.Identity();
  54558. if (prefiltered) {
  54559. _this.gammaSpace = false;
  54560. }
  54561. if (!rootUrl && !files) {
  54562. return _this;
  54563. }
  54564. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  54565. var lastDot = rootUrl.lastIndexOf(".");
  54566. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  54567. var isDDS = (extension === ".dds");
  54568. if (!files) {
  54569. if (!isDDS && !extensions) {
  54570. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  54571. }
  54572. files = [];
  54573. if (extensions) {
  54574. for (var index = 0; index < extensions.length; index++) {
  54575. files.push(rootUrl + extensions[index]);
  54576. }
  54577. }
  54578. }
  54579. _this._files = files;
  54580. if (!_this._texture) {
  54581. if (!scene.useDelayedTextureLoading) {
  54582. if (prefiltered) {
  54583. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  54584. }
  54585. else {
  54586. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  54587. }
  54588. }
  54589. else {
  54590. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  54591. }
  54592. }
  54593. else if (onLoad) {
  54594. if (_this._texture.isReady) {
  54595. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  54596. }
  54597. else {
  54598. _this._texture.onLoadedObservable.add(onLoad);
  54599. }
  54600. }
  54601. return _this;
  54602. }
  54603. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  54604. return new CubeTexture("", scene, null, noMipmap, files);
  54605. };
  54606. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  54607. if (forcedExtension === void 0) { forcedExtension = null; }
  54608. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  54609. };
  54610. // Methods
  54611. CubeTexture.prototype.delayLoad = function () {
  54612. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  54613. return;
  54614. }
  54615. var scene = this.getScene();
  54616. if (!scene) {
  54617. return;
  54618. }
  54619. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  54620. this._texture = this._getFromCache(this.url, this._noMipmap);
  54621. if (!this._texture) {
  54622. if (this._prefiltered) {
  54623. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  54624. }
  54625. else {
  54626. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  54627. }
  54628. }
  54629. };
  54630. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  54631. return this._textureMatrix;
  54632. };
  54633. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  54634. this._textureMatrix = value;
  54635. };
  54636. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  54637. var texture = BABYLON.SerializationHelper.Parse(function () {
  54638. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  54639. }, parsedTexture, scene);
  54640. // Animations
  54641. if (parsedTexture.animations) {
  54642. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  54643. var parsedAnimation = parsedTexture.animations[animationIndex];
  54644. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  54645. }
  54646. }
  54647. return texture;
  54648. };
  54649. CubeTexture.prototype.clone = function () {
  54650. var _this = this;
  54651. return BABYLON.SerializationHelper.Clone(function () {
  54652. var scene = _this.getScene();
  54653. if (!scene) {
  54654. return _this;
  54655. }
  54656. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  54657. }, this);
  54658. };
  54659. return CubeTexture;
  54660. }(BABYLON.BaseTexture));
  54661. BABYLON.CubeTexture = CubeTexture;
  54662. })(BABYLON || (BABYLON = {}));
  54663. //# sourceMappingURL=babylon.cubeTexture.js.map
  54664. var BABYLON;
  54665. (function (BABYLON) {
  54666. var RenderTargetTexture = /** @class */ (function (_super) {
  54667. __extends(RenderTargetTexture, _super);
  54668. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  54669. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  54670. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54671. if (isCube === void 0) { isCube = false; }
  54672. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54673. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54674. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  54675. if (isMulti === void 0) { isMulti = false; }
  54676. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54677. _this.isCube = isCube;
  54678. /**
  54679. * Use this list to define the list of mesh you want to render.
  54680. */
  54681. _this.renderList = new Array();
  54682. _this.renderParticles = true;
  54683. _this.renderSprites = false;
  54684. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  54685. _this.ignoreCameraViewport = false;
  54686. // Events
  54687. /**
  54688. * An event triggered when the texture is unbind.
  54689. * @type {BABYLON.Observable}
  54690. */
  54691. _this.onBeforeBindObservable = new BABYLON.Observable();
  54692. /**
  54693. * An event triggered when the texture is unbind.
  54694. * @type {BABYLON.Observable}
  54695. */
  54696. _this.onAfterUnbindObservable = new BABYLON.Observable();
  54697. /**
  54698. * An event triggered before rendering the texture
  54699. * @type {BABYLON.Observable}
  54700. */
  54701. _this.onBeforeRenderObservable = new BABYLON.Observable();
  54702. /**
  54703. * An event triggered after rendering the texture
  54704. * @type {BABYLON.Observable}
  54705. */
  54706. _this.onAfterRenderObservable = new BABYLON.Observable();
  54707. /**
  54708. * An event triggered after the texture clear
  54709. * @type {BABYLON.Observable}
  54710. */
  54711. _this.onClearObservable = new BABYLON.Observable();
  54712. _this._currentRefreshId = -1;
  54713. _this._refreshRate = 1;
  54714. _this._samples = 1;
  54715. scene = _this.getScene();
  54716. if (!scene) {
  54717. return _this;
  54718. }
  54719. _this._engine = scene.getEngine();
  54720. _this.name = name;
  54721. _this.isRenderTarget = true;
  54722. _this._initialSizeParameter = size;
  54723. _this._processSizeParameter(size);
  54724. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  54725. });
  54726. _this._generateMipMaps = generateMipMaps ? true : false;
  54727. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  54728. // Rendering groups
  54729. _this._renderingManager = new BABYLON.RenderingManager(scene);
  54730. if (isMulti) {
  54731. return _this;
  54732. }
  54733. _this._renderTargetOptions = {
  54734. generateMipMaps: generateMipMaps,
  54735. type: type,
  54736. samplingMode: samplingMode,
  54737. generateDepthBuffer: generateDepthBuffer,
  54738. generateStencilBuffer: generateStencilBuffer
  54739. };
  54740. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  54741. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54742. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54743. }
  54744. if (isCube) {
  54745. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  54746. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  54747. _this._textureMatrix = BABYLON.Matrix.Identity();
  54748. }
  54749. else {
  54750. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  54751. }
  54752. return _this;
  54753. }
  54754. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  54755. get: function () {
  54756. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  54757. },
  54758. enumerable: true,
  54759. configurable: true
  54760. });
  54761. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  54762. get: function () {
  54763. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  54764. },
  54765. enumerable: true,
  54766. configurable: true
  54767. });
  54768. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  54769. get: function () {
  54770. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  54771. },
  54772. enumerable: true,
  54773. configurable: true
  54774. });
  54775. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  54776. set: function (callback) {
  54777. if (this._onAfterUnbindObserver) {
  54778. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  54779. }
  54780. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  54781. },
  54782. enumerable: true,
  54783. configurable: true
  54784. });
  54785. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  54786. set: function (callback) {
  54787. if (this._onBeforeRenderObserver) {
  54788. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  54789. }
  54790. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  54791. },
  54792. enumerable: true,
  54793. configurable: true
  54794. });
  54795. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  54796. set: function (callback) {
  54797. if (this._onAfterRenderObserver) {
  54798. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  54799. }
  54800. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  54801. },
  54802. enumerable: true,
  54803. configurable: true
  54804. });
  54805. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  54806. set: function (callback) {
  54807. if (this._onClearObserver) {
  54808. this.onClearObservable.remove(this._onClearObserver);
  54809. }
  54810. this._onClearObserver = this.onClearObservable.add(callback);
  54811. },
  54812. enumerable: true,
  54813. configurable: true
  54814. });
  54815. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  54816. get: function () {
  54817. return this._renderTargetOptions;
  54818. },
  54819. enumerable: true,
  54820. configurable: true
  54821. });
  54822. RenderTargetTexture.prototype._onRatioRescale = function () {
  54823. if (this._sizeRatio) {
  54824. this.resize(this._initialSizeParameter);
  54825. }
  54826. };
  54827. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  54828. if (size.ratio) {
  54829. this._sizeRatio = size.ratio;
  54830. this._size = {
  54831. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  54832. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  54833. };
  54834. }
  54835. else {
  54836. this._size = size;
  54837. }
  54838. };
  54839. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  54840. get: function () {
  54841. return this._samples;
  54842. },
  54843. set: function (value) {
  54844. if (this._samples === value) {
  54845. return;
  54846. }
  54847. var scene = this.getScene();
  54848. if (!scene) {
  54849. return;
  54850. }
  54851. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  54852. },
  54853. enumerable: true,
  54854. configurable: true
  54855. });
  54856. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  54857. this._currentRefreshId = -1;
  54858. };
  54859. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  54860. get: function () {
  54861. return this._refreshRate;
  54862. },
  54863. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54864. set: function (value) {
  54865. this._refreshRate = value;
  54866. this.resetRefreshCounter();
  54867. },
  54868. enumerable: true,
  54869. configurable: true
  54870. });
  54871. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  54872. if (!this._postProcessManager) {
  54873. var scene = this.getScene();
  54874. if (!scene) {
  54875. return;
  54876. }
  54877. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  54878. this._postProcesses = new Array();
  54879. }
  54880. this._postProcesses.push(postProcess);
  54881. this._postProcesses[0].autoClear = false;
  54882. };
  54883. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  54884. if (!this._postProcesses) {
  54885. return;
  54886. }
  54887. if (dispose) {
  54888. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  54889. var postProcess = _a[_i];
  54890. postProcess.dispose();
  54891. }
  54892. }
  54893. this._postProcesses = [];
  54894. };
  54895. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  54896. if (!this._postProcesses) {
  54897. return;
  54898. }
  54899. var index = this._postProcesses.indexOf(postProcess);
  54900. if (index === -1) {
  54901. return;
  54902. }
  54903. this._postProcesses.splice(index, 1);
  54904. if (this._postProcesses.length > 0) {
  54905. this._postProcesses[0].autoClear = false;
  54906. }
  54907. };
  54908. RenderTargetTexture.prototype._shouldRender = function () {
  54909. if (this._currentRefreshId === -1) {
  54910. this._currentRefreshId = 1;
  54911. return true;
  54912. }
  54913. if (this.refreshRate === this._currentRefreshId) {
  54914. this._currentRefreshId = 1;
  54915. return true;
  54916. }
  54917. this._currentRefreshId++;
  54918. return false;
  54919. };
  54920. RenderTargetTexture.prototype.getRenderSize = function () {
  54921. if (this._size.width) {
  54922. return this._size.width;
  54923. }
  54924. return this._size;
  54925. };
  54926. RenderTargetTexture.prototype.getRenderWidth = function () {
  54927. if (this._size.width) {
  54928. return this._size.width;
  54929. }
  54930. return this._size;
  54931. };
  54932. RenderTargetTexture.prototype.getRenderHeight = function () {
  54933. if (this._size.width) {
  54934. return this._size.height;
  54935. }
  54936. return this._size;
  54937. };
  54938. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  54939. get: function () {
  54940. return true;
  54941. },
  54942. enumerable: true,
  54943. configurable: true
  54944. });
  54945. RenderTargetTexture.prototype.scale = function (ratio) {
  54946. var newSize = this.getRenderSize() * ratio;
  54947. this.resize(newSize);
  54948. };
  54949. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  54950. if (this.isCube) {
  54951. return this._textureMatrix;
  54952. }
  54953. return _super.prototype.getReflectionTextureMatrix.call(this);
  54954. };
  54955. RenderTargetTexture.prototype.resize = function (size) {
  54956. this.releaseInternalTexture();
  54957. var scene = this.getScene();
  54958. if (!scene) {
  54959. return;
  54960. }
  54961. this._processSizeParameter(size);
  54962. if (this.isCube) {
  54963. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  54964. }
  54965. else {
  54966. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  54967. }
  54968. };
  54969. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  54970. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  54971. if (dumpForDebug === void 0) { dumpForDebug = false; }
  54972. var scene = this.getScene();
  54973. if (!scene) {
  54974. return;
  54975. }
  54976. var engine = scene.getEngine();
  54977. if (this.useCameraPostProcesses !== undefined) {
  54978. useCameraPostProcess = this.useCameraPostProcesses;
  54979. }
  54980. if (this._waitingRenderList) {
  54981. this.renderList = [];
  54982. for (var index = 0; index < this._waitingRenderList.length; index++) {
  54983. var id = this._waitingRenderList[index];
  54984. var mesh_1 = scene.getMeshByID(id);
  54985. if (mesh_1) {
  54986. this.renderList.push(mesh_1);
  54987. }
  54988. }
  54989. delete this._waitingRenderList;
  54990. }
  54991. // Is predicate defined?
  54992. if (this.renderListPredicate) {
  54993. if (this.renderList) {
  54994. this.renderList.splice(0); // Clear previous renderList
  54995. }
  54996. else {
  54997. this.renderList = [];
  54998. }
  54999. var scene = this.getScene();
  55000. if (!scene) {
  55001. return;
  55002. }
  55003. var sceneMeshes = scene.meshes;
  55004. for (var index = 0; index < sceneMeshes.length; index++) {
  55005. var mesh = sceneMeshes[index];
  55006. if (this.renderListPredicate(mesh)) {
  55007. this.renderList.push(mesh);
  55008. }
  55009. }
  55010. }
  55011. this.onBeforeBindObservable.notifyObservers(this);
  55012. // Set custom projection.
  55013. // Needs to be before binding to prevent changing the aspect ratio.
  55014. var camera;
  55015. if (this.activeCamera) {
  55016. camera = this.activeCamera;
  55017. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  55018. if (this.activeCamera !== scene.activeCamera) {
  55019. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  55020. }
  55021. }
  55022. else {
  55023. camera = scene.activeCamera;
  55024. if (camera) {
  55025. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  55026. }
  55027. }
  55028. // Prepare renderingManager
  55029. this._renderingManager.reset();
  55030. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  55031. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  55032. var sceneRenderId = scene.getRenderId();
  55033. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  55034. var mesh = currentRenderList[meshIndex];
  55035. if (mesh) {
  55036. if (!mesh.isReady()) {
  55037. // Reset _currentRefreshId
  55038. this.resetRefreshCounter();
  55039. continue;
  55040. }
  55041. mesh._preActivateForIntermediateRendering(sceneRenderId);
  55042. var isMasked = void 0;
  55043. if (!this.renderList && camera) {
  55044. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  55045. }
  55046. else {
  55047. isMasked = false;
  55048. }
  55049. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  55050. mesh._activate(sceneRenderId);
  55051. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  55052. var subMesh = mesh.subMeshes[subIndex];
  55053. scene._activeIndices.addCount(subMesh.indexCount, false);
  55054. this._renderingManager.dispatch(subMesh, mesh);
  55055. }
  55056. }
  55057. }
  55058. }
  55059. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  55060. var particleSystem = scene.particleSystems[particleIndex];
  55061. var emitter = particleSystem.emitter;
  55062. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  55063. continue;
  55064. }
  55065. if (currentRenderList.indexOf(emitter) >= 0) {
  55066. this._renderingManager.dispatchParticles(particleSystem);
  55067. }
  55068. }
  55069. if (this.isCube) {
  55070. for (var face = 0; face < 6; face++) {
  55071. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  55072. scene.incrementRenderId();
  55073. scene.resetCachedMaterial();
  55074. }
  55075. }
  55076. else {
  55077. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  55078. }
  55079. this.onAfterUnbindObservable.notifyObservers(this);
  55080. if (scene.activeCamera) {
  55081. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  55082. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  55083. }
  55084. engine.setViewport(scene.activeCamera.viewport);
  55085. }
  55086. scene.resetCachedMaterial();
  55087. };
  55088. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  55089. var minimum = 128;
  55090. var x = renderDimension * scale;
  55091. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  55092. // Ensure we don't exceed the render dimension (while staying POT)
  55093. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  55094. };
  55095. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  55096. var _this = this;
  55097. if (!this._texture) {
  55098. return;
  55099. }
  55100. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  55101. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  55102. });
  55103. };
  55104. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  55105. var scene = this.getScene();
  55106. if (!scene) {
  55107. return;
  55108. }
  55109. var engine = scene.getEngine();
  55110. if (!this._texture) {
  55111. return;
  55112. }
  55113. // Bind
  55114. if (this._postProcessManager) {
  55115. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  55116. }
  55117. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  55118. if (this._texture) {
  55119. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  55120. }
  55121. }
  55122. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  55123. // Clear
  55124. if (this.onClearObservable.hasObservers()) {
  55125. this.onClearObservable.notifyObservers(engine);
  55126. }
  55127. else {
  55128. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  55129. }
  55130. if (!this._doNotChangeAspectRatio) {
  55131. scene.updateTransformMatrix(true);
  55132. }
  55133. // Render
  55134. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  55135. if (this._postProcessManager) {
  55136. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  55137. }
  55138. else if (useCameraPostProcess) {
  55139. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  55140. }
  55141. if (!this._doNotChangeAspectRatio) {
  55142. scene.updateTransformMatrix(true);
  55143. }
  55144. // Dump ?
  55145. if (dumpForDebug) {
  55146. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  55147. }
  55148. // Unbind
  55149. if (!this.isCube || faceIndex === 5) {
  55150. if (this.isCube) {
  55151. if (faceIndex === 5) {
  55152. engine.generateMipMapsForCubemap(this._texture);
  55153. }
  55154. }
  55155. this.unbindFrameBuffer(engine, faceIndex);
  55156. }
  55157. else {
  55158. this.onAfterRenderObservable.notifyObservers(faceIndex);
  55159. }
  55160. };
  55161. /**
  55162. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  55163. * This allowed control for front to back rendering or reversly depending of the special needs.
  55164. *
  55165. * @param renderingGroupId The rendering group id corresponding to its index
  55166. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  55167. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  55168. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  55169. */
  55170. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  55171. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  55172. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  55173. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  55174. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  55175. };
  55176. /**
  55177. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  55178. *
  55179. * @param renderingGroupId The rendering group id corresponding to its index
  55180. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  55181. */
  55182. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  55183. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  55184. };
  55185. RenderTargetTexture.prototype.clone = function () {
  55186. var textureSize = this.getSize();
  55187. 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);
  55188. // Base texture
  55189. newTexture.hasAlpha = this.hasAlpha;
  55190. newTexture.level = this.level;
  55191. // RenderTarget Texture
  55192. newTexture.coordinatesMode = this.coordinatesMode;
  55193. if (this.renderList) {
  55194. newTexture.renderList = this.renderList.slice(0);
  55195. }
  55196. return newTexture;
  55197. };
  55198. RenderTargetTexture.prototype.serialize = function () {
  55199. if (!this.name) {
  55200. return null;
  55201. }
  55202. var serializationObject = _super.prototype.serialize.call(this);
  55203. serializationObject.renderTargetSize = this.getRenderSize();
  55204. serializationObject.renderList = [];
  55205. if (this.renderList) {
  55206. for (var index = 0; index < this.renderList.length; index++) {
  55207. serializationObject.renderList.push(this.renderList[index].id);
  55208. }
  55209. }
  55210. return serializationObject;
  55211. };
  55212. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  55213. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  55214. var objBuffer = this.getInternalTexture();
  55215. var scene = this.getScene();
  55216. if (objBuffer && scene) {
  55217. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  55218. }
  55219. };
  55220. RenderTargetTexture.prototype.dispose = function () {
  55221. if (this._postProcessManager) {
  55222. this._postProcessManager.dispose();
  55223. this._postProcessManager = null;
  55224. }
  55225. this.clearPostProcesses(true);
  55226. if (this._resizeObserver) {
  55227. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  55228. this._resizeObserver = null;
  55229. }
  55230. this.renderList = null;
  55231. // Remove from custom render targets
  55232. var scene = this.getScene();
  55233. if (!scene) {
  55234. return;
  55235. }
  55236. var index = scene.customRenderTargets.indexOf(this);
  55237. if (index >= 0) {
  55238. scene.customRenderTargets.splice(index, 1);
  55239. }
  55240. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  55241. var camera = _a[_i];
  55242. index = camera.customRenderTargets.indexOf(this);
  55243. if (index >= 0) {
  55244. camera.customRenderTargets.splice(index, 1);
  55245. }
  55246. }
  55247. _super.prototype.dispose.call(this);
  55248. };
  55249. RenderTargetTexture.prototype._rebuild = function () {
  55250. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55251. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55252. }
  55253. if (this._postProcessManager) {
  55254. this._postProcessManager._rebuild();
  55255. }
  55256. };
  55257. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  55258. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  55259. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  55260. return RenderTargetTexture;
  55261. }(BABYLON.Texture));
  55262. BABYLON.RenderTargetTexture = RenderTargetTexture;
  55263. })(BABYLON || (BABYLON = {}));
  55264. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  55265. var BABYLON;
  55266. (function (BABYLON) {
  55267. ;
  55268. var MultiRenderTarget = /** @class */ (function (_super) {
  55269. __extends(MultiRenderTarget, _super);
  55270. function MultiRenderTarget(name, size, count, scene, options) {
  55271. var _this = this;
  55272. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  55273. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  55274. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  55275. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  55276. _this._engine = scene.getEngine();
  55277. if (!_this.isSupported) {
  55278. _this.dispose();
  55279. return;
  55280. }
  55281. var types = [];
  55282. var samplingModes = [];
  55283. for (var i = 0; i < count; i++) {
  55284. if (options && options.types && options.types[i] !== undefined) {
  55285. types.push(options.types[i]);
  55286. }
  55287. else {
  55288. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55289. }
  55290. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  55291. samplingModes.push(options.samplingModes[i]);
  55292. }
  55293. else {
  55294. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55295. }
  55296. }
  55297. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  55298. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  55299. _this._size = size;
  55300. _this._multiRenderTargetOptions = {
  55301. samplingModes: samplingModes,
  55302. generateMipMaps: generateMipMaps,
  55303. generateDepthBuffer: generateDepthBuffer,
  55304. generateStencilBuffer: generateStencilBuffer,
  55305. generateDepthTexture: generateDepthTexture,
  55306. types: types,
  55307. textureCount: count
  55308. };
  55309. _this._createInternalTextures();
  55310. _this._createTextures();
  55311. return _this;
  55312. }
  55313. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  55314. get: function () {
  55315. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  55316. },
  55317. enumerable: true,
  55318. configurable: true
  55319. });
  55320. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  55321. get: function () {
  55322. return this._textures;
  55323. },
  55324. enumerable: true,
  55325. configurable: true
  55326. });
  55327. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  55328. get: function () {
  55329. return this._textures[this._textures.length - 1];
  55330. },
  55331. enumerable: true,
  55332. configurable: true
  55333. });
  55334. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  55335. set: function (wrap) {
  55336. if (this._textures) {
  55337. for (var i = 0; i < this._textures.length; i++) {
  55338. this._textures[i].wrapU = wrap;
  55339. }
  55340. }
  55341. },
  55342. enumerable: true,
  55343. configurable: true
  55344. });
  55345. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  55346. set: function (wrap) {
  55347. if (this._textures) {
  55348. for (var i = 0; i < this._textures.length; i++) {
  55349. this._textures[i].wrapV = wrap;
  55350. }
  55351. }
  55352. },
  55353. enumerable: true,
  55354. configurable: true
  55355. });
  55356. MultiRenderTarget.prototype._rebuild = function () {
  55357. this.releaseInternalTextures();
  55358. this._createInternalTextures();
  55359. for (var i = 0; i < this._internalTextures.length; i++) {
  55360. var texture = this._textures[i];
  55361. texture._texture = this._internalTextures[i];
  55362. }
  55363. // Keeps references to frame buffer and stencil/depth buffer
  55364. this._texture = this._internalTextures[0];
  55365. };
  55366. MultiRenderTarget.prototype._createInternalTextures = function () {
  55367. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  55368. };
  55369. MultiRenderTarget.prototype._createTextures = function () {
  55370. this._textures = [];
  55371. for (var i = 0; i < this._internalTextures.length; i++) {
  55372. var texture = new BABYLON.Texture(null, this.getScene());
  55373. texture._texture = this._internalTextures[i];
  55374. this._textures.push(texture);
  55375. }
  55376. // Keeps references to frame buffer and stencil/depth buffer
  55377. this._texture = this._internalTextures[0];
  55378. };
  55379. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  55380. get: function () {
  55381. return this._samples;
  55382. },
  55383. set: function (value) {
  55384. if (this._samples === value) {
  55385. return;
  55386. }
  55387. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  55388. },
  55389. enumerable: true,
  55390. configurable: true
  55391. });
  55392. MultiRenderTarget.prototype.resize = function (size) {
  55393. this.releaseInternalTextures();
  55394. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  55395. this._createInternalTextures();
  55396. };
  55397. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  55398. var _this = this;
  55399. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  55400. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  55401. });
  55402. };
  55403. MultiRenderTarget.prototype.dispose = function () {
  55404. this.releaseInternalTextures();
  55405. _super.prototype.dispose.call(this);
  55406. };
  55407. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  55408. if (!this._internalTextures) {
  55409. return;
  55410. }
  55411. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  55412. if (this._internalTextures[i] !== undefined) {
  55413. this._internalTextures[i].dispose();
  55414. this._internalTextures.splice(i, 1);
  55415. }
  55416. }
  55417. };
  55418. return MultiRenderTarget;
  55419. }(BABYLON.RenderTargetTexture));
  55420. BABYLON.MultiRenderTarget = MultiRenderTarget;
  55421. })(BABYLON || (BABYLON = {}));
  55422. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  55423. var BABYLON;
  55424. (function (BABYLON) {
  55425. var MirrorTexture = /** @class */ (function (_super) {
  55426. __extends(MirrorTexture, _super);
  55427. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  55428. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55429. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55430. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  55431. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  55432. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  55433. _this._transformMatrix = BABYLON.Matrix.Zero();
  55434. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  55435. _this._adaptiveBlurKernel = 0;
  55436. _this._blurKernelX = 0;
  55437. _this._blurKernelY = 0;
  55438. _this._blurRatio = 1.0;
  55439. _this.ignoreCameraViewport = true;
  55440. _this.onBeforeRenderObservable.add(function () {
  55441. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  55442. _this._savedViewMatrix = scene.getViewMatrix();
  55443. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  55444. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  55445. scene.clipPlane = _this.mirrorPlane;
  55446. scene.getEngine().cullBackFaces = false;
  55447. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  55448. });
  55449. _this.onAfterRenderObservable.add(function () {
  55450. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  55451. scene.getEngine().cullBackFaces = true;
  55452. scene._mirroredCameraPosition = null;
  55453. delete scene.clipPlane;
  55454. });
  55455. return _this;
  55456. }
  55457. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  55458. get: function () {
  55459. return this._blurRatio;
  55460. },
  55461. set: function (value) {
  55462. if (this._blurRatio === value) {
  55463. return;
  55464. }
  55465. this._blurRatio = value;
  55466. this._preparePostProcesses();
  55467. },
  55468. enumerable: true,
  55469. configurable: true
  55470. });
  55471. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  55472. set: function (value) {
  55473. this._adaptiveBlurKernel = value;
  55474. this._autoComputeBlurKernel();
  55475. },
  55476. enumerable: true,
  55477. configurable: true
  55478. });
  55479. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  55480. set: function (value) {
  55481. this.blurKernelX = value;
  55482. this.blurKernelY = value;
  55483. },
  55484. enumerable: true,
  55485. configurable: true
  55486. });
  55487. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  55488. get: function () {
  55489. return this._blurKernelX;
  55490. },
  55491. set: function (value) {
  55492. if (this._blurKernelX === value) {
  55493. return;
  55494. }
  55495. this._blurKernelX = value;
  55496. this._preparePostProcesses();
  55497. },
  55498. enumerable: true,
  55499. configurable: true
  55500. });
  55501. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  55502. get: function () {
  55503. return this._blurKernelY;
  55504. },
  55505. set: function (value) {
  55506. if (this._blurKernelY === value) {
  55507. return;
  55508. }
  55509. this._blurKernelY = value;
  55510. this._preparePostProcesses();
  55511. },
  55512. enumerable: true,
  55513. configurable: true
  55514. });
  55515. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  55516. var engine = this.getScene().getEngine();
  55517. var dw = this.getRenderWidth() / engine.getRenderWidth();
  55518. var dh = this.getRenderHeight() / engine.getRenderHeight();
  55519. this.blurKernelX = this._adaptiveBlurKernel * dw;
  55520. this.blurKernelY = this._adaptiveBlurKernel * dh;
  55521. };
  55522. MirrorTexture.prototype._onRatioRescale = function () {
  55523. if (this._sizeRatio) {
  55524. this.resize(this._initialSizeParameter);
  55525. if (!this._adaptiveBlurKernel) {
  55526. this._preparePostProcesses();
  55527. }
  55528. }
  55529. if (this._adaptiveBlurKernel) {
  55530. this._autoComputeBlurKernel();
  55531. }
  55532. };
  55533. MirrorTexture.prototype._preparePostProcesses = function () {
  55534. this.clearPostProcesses(true);
  55535. if (this._blurKernelX && this._blurKernelY) {
  55536. var engine = this.getScene().getEngine();
  55537. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55538. 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);
  55539. this._blurX.autoClear = false;
  55540. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  55541. this._blurX.outputTexture = this._texture;
  55542. }
  55543. else {
  55544. this._blurX.alwaysForcePOT = true;
  55545. }
  55546. 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);
  55547. this._blurY.autoClear = false;
  55548. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  55549. this.addPostProcess(this._blurX);
  55550. this.addPostProcess(this._blurY);
  55551. }
  55552. else {
  55553. if (this._blurY) {
  55554. this.removePostProcess(this._blurY);
  55555. this._blurY.dispose();
  55556. this._blurY = null;
  55557. }
  55558. if (this._blurX) {
  55559. this.removePostProcess(this._blurX);
  55560. this._blurX.dispose();
  55561. this._blurX = null;
  55562. }
  55563. }
  55564. };
  55565. MirrorTexture.prototype.clone = function () {
  55566. var scene = this.getScene();
  55567. if (!scene) {
  55568. return this;
  55569. }
  55570. var textureSize = this.getSize();
  55571. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  55572. // Base texture
  55573. newTexture.hasAlpha = this.hasAlpha;
  55574. newTexture.level = this.level;
  55575. // Mirror Texture
  55576. newTexture.mirrorPlane = this.mirrorPlane.clone();
  55577. if (this.renderList) {
  55578. newTexture.renderList = this.renderList.slice(0);
  55579. }
  55580. return newTexture;
  55581. };
  55582. MirrorTexture.prototype.serialize = function () {
  55583. if (!this.name) {
  55584. return null;
  55585. }
  55586. var serializationObject = _super.prototype.serialize.call(this);
  55587. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  55588. return serializationObject;
  55589. };
  55590. return MirrorTexture;
  55591. }(BABYLON.RenderTargetTexture));
  55592. BABYLON.MirrorTexture = MirrorTexture;
  55593. })(BABYLON || (BABYLON = {}));
  55594. //# sourceMappingURL=babylon.mirrorTexture.js.map
  55595. var BABYLON;
  55596. (function (BABYLON) {
  55597. /**
  55598. * Creates a refraction texture used by refraction channel of the standard material.
  55599. * @param name the texture name
  55600. * @param size size of the underlying texture
  55601. * @param scene root scene
  55602. */
  55603. var RefractionTexture = /** @class */ (function (_super) {
  55604. __extends(RefractionTexture, _super);
  55605. function RefractionTexture(name, size, scene, generateMipMaps) {
  55606. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  55607. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  55608. _this.depth = 2.0;
  55609. _this.onBeforeRenderObservable.add(function () {
  55610. scene.clipPlane = _this.refractionPlane;
  55611. });
  55612. _this.onAfterRenderObservable.add(function () {
  55613. delete scene.clipPlane;
  55614. });
  55615. return _this;
  55616. }
  55617. RefractionTexture.prototype.clone = function () {
  55618. var scene = this.getScene();
  55619. if (!scene) {
  55620. return this;
  55621. }
  55622. var textureSize = this.getSize();
  55623. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  55624. // Base texture
  55625. newTexture.hasAlpha = this.hasAlpha;
  55626. newTexture.level = this.level;
  55627. // Refraction Texture
  55628. newTexture.refractionPlane = this.refractionPlane.clone();
  55629. if (this.renderList) {
  55630. newTexture.renderList = this.renderList.slice(0);
  55631. }
  55632. newTexture.depth = this.depth;
  55633. return newTexture;
  55634. };
  55635. RefractionTexture.prototype.serialize = function () {
  55636. if (!this.name) {
  55637. return null;
  55638. }
  55639. var serializationObject = _super.prototype.serialize.call(this);
  55640. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  55641. serializationObject.depth = this.depth;
  55642. return serializationObject;
  55643. };
  55644. return RefractionTexture;
  55645. }(BABYLON.RenderTargetTexture));
  55646. BABYLON.RefractionTexture = RefractionTexture;
  55647. })(BABYLON || (BABYLON = {}));
  55648. //# sourceMappingURL=babylon.refractionTexture.js.map
  55649. var BABYLON;
  55650. (function (BABYLON) {
  55651. var DynamicTexture = /** @class */ (function (_super) {
  55652. __extends(DynamicTexture, _super);
  55653. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  55654. if (scene === void 0) { scene = null; }
  55655. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55656. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55657. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  55658. _this.name = name;
  55659. _this._engine = _this.getScene().getEngine();
  55660. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55661. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55662. _this._generateMipMaps = generateMipMaps;
  55663. if (options.getContext) {
  55664. _this._canvas = options;
  55665. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55666. }
  55667. else {
  55668. _this._canvas = document.createElement("canvas");
  55669. if (options.width) {
  55670. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55671. }
  55672. else {
  55673. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  55674. }
  55675. }
  55676. var textureSize = _this.getSize();
  55677. _this._canvas.width = textureSize.width;
  55678. _this._canvas.height = textureSize.height;
  55679. _this._context = _this._canvas.getContext("2d");
  55680. return _this;
  55681. }
  55682. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  55683. get: function () {
  55684. return true;
  55685. },
  55686. enumerable: true,
  55687. configurable: true
  55688. });
  55689. DynamicTexture.prototype._recreate = function (textureSize) {
  55690. this._canvas.width = textureSize.width;
  55691. this._canvas.height = textureSize.height;
  55692. this.releaseInternalTexture();
  55693. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  55694. };
  55695. DynamicTexture.prototype.scale = function (ratio) {
  55696. var textureSize = this.getSize();
  55697. textureSize.width *= ratio;
  55698. textureSize.height *= ratio;
  55699. this._recreate(textureSize);
  55700. };
  55701. DynamicTexture.prototype.scaleTo = function (width, height) {
  55702. var textureSize = this.getSize();
  55703. textureSize.width = width;
  55704. textureSize.height = height;
  55705. this._recreate(textureSize);
  55706. };
  55707. DynamicTexture.prototype.getContext = function () {
  55708. return this._context;
  55709. };
  55710. DynamicTexture.prototype.clear = function () {
  55711. var size = this.getSize();
  55712. this._context.fillRect(0, 0, size.width, size.height);
  55713. };
  55714. DynamicTexture.prototype.update = function (invertY) {
  55715. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  55716. };
  55717. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  55718. if (update === void 0) { update = true; }
  55719. var size = this.getSize();
  55720. if (clearColor) {
  55721. this._context.fillStyle = clearColor;
  55722. this._context.fillRect(0, 0, size.width, size.height);
  55723. }
  55724. this._context.font = font;
  55725. if (x === null || x === undefined) {
  55726. var textSize = this._context.measureText(text);
  55727. x = (size.width - textSize.width) / 2;
  55728. }
  55729. if (y === null || y === undefined) {
  55730. var fontSize = parseInt((font.replace(/\D/g, '')));
  55731. ;
  55732. y = (size.height / 2) + (fontSize / 3.65);
  55733. }
  55734. this._context.fillStyle = color;
  55735. this._context.fillText(text, x, y);
  55736. if (update) {
  55737. this.update(invertY);
  55738. }
  55739. };
  55740. DynamicTexture.prototype.clone = function () {
  55741. var scene = this.getScene();
  55742. if (!scene) {
  55743. return this;
  55744. }
  55745. var textureSize = this.getSize();
  55746. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  55747. // Base texture
  55748. newTexture.hasAlpha = this.hasAlpha;
  55749. newTexture.level = this.level;
  55750. // Dynamic Texture
  55751. newTexture.wrapU = this.wrapU;
  55752. newTexture.wrapV = this.wrapV;
  55753. return newTexture;
  55754. };
  55755. DynamicTexture.prototype._rebuild = function () {
  55756. this.update();
  55757. };
  55758. return DynamicTexture;
  55759. }(BABYLON.Texture));
  55760. BABYLON.DynamicTexture = DynamicTexture;
  55761. })(BABYLON || (BABYLON = {}));
  55762. //# sourceMappingURL=babylon.dynamicTexture.js.map
  55763. var BABYLON;
  55764. (function (BABYLON) {
  55765. var VideoTexture = /** @class */ (function (_super) {
  55766. __extends(VideoTexture, _super);
  55767. /**
  55768. * Creates a video texture.
  55769. * Sample : https://doc.babylonjs.com/how_to/video_texture
  55770. * @param {string | null} name optional name, will detect from video source, if not defined
  55771. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  55772. * @param {BABYLON.Scene} scene is obviously the current scene.
  55773. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  55774. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  55775. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  55776. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  55777. */
  55778. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  55779. if (generateMipMaps === void 0) { generateMipMaps = false; }
  55780. if (invertY === void 0) { invertY = false; }
  55781. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55782. if (settings === void 0) { settings = {
  55783. autoPlay: true,
  55784. loop: true,
  55785. autoUpdateTexture: true,
  55786. }; }
  55787. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55788. _this._createInternalTexture = function () {
  55789. if (_this._texture != null) {
  55790. return;
  55791. }
  55792. if (!_this._engine.needPOTTextures ||
  55793. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  55794. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55795. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55796. }
  55797. else {
  55798. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55799. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55800. _this._generateMipMaps = false;
  55801. }
  55802. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  55803. _this._texture.isReady = true;
  55804. _this._updateInternalTexture();
  55805. };
  55806. _this.reset = function () {
  55807. if (_this._texture == null) {
  55808. return;
  55809. }
  55810. _this._texture.dispose();
  55811. _this._texture = null;
  55812. };
  55813. _this._updateInternalTexture = function (e) {
  55814. if (_this._texture == null || !_this._texture.isReady) {
  55815. return;
  55816. }
  55817. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  55818. return;
  55819. }
  55820. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  55821. };
  55822. _this._engine = _this.getScene().getEngine();
  55823. _this._generateMipMaps = generateMipMaps;
  55824. _this._samplingMode = samplingMode;
  55825. _this.autoUpdateTexture = settings.autoUpdateTexture;
  55826. _this.name = name || _this._getName(src);
  55827. _this.video = _this._getVideo(src);
  55828. if (settings.autoPlay !== undefined) {
  55829. _this.video.autoplay = settings.autoPlay;
  55830. }
  55831. if (settings.loop !== undefined) {
  55832. _this.video.loop = settings.loop;
  55833. }
  55834. _this.video.addEventListener("canplay", _this._createInternalTexture);
  55835. _this.video.addEventListener("paused", _this._updateInternalTexture);
  55836. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  55837. _this.video.addEventListener("emptied", _this.reset);
  55838. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  55839. _this._createInternalTexture();
  55840. }
  55841. return _this;
  55842. }
  55843. VideoTexture.prototype._getName = function (src) {
  55844. if (src instanceof HTMLVideoElement) {
  55845. return src.currentSrc;
  55846. }
  55847. if (typeof src === "object") {
  55848. return src.toString();
  55849. }
  55850. return src;
  55851. };
  55852. ;
  55853. VideoTexture.prototype._getVideo = function (src) {
  55854. if (src instanceof HTMLVideoElement) {
  55855. return src;
  55856. }
  55857. var video = document.createElement("video");
  55858. if (typeof src === "string") {
  55859. video.src = src;
  55860. }
  55861. else {
  55862. src.forEach(function (url) {
  55863. var source = document.createElement("source");
  55864. source.src = url;
  55865. video.appendChild(source);
  55866. });
  55867. }
  55868. return video;
  55869. };
  55870. ;
  55871. /**
  55872. * Internal method to initiate `update`.
  55873. */
  55874. VideoTexture.prototype._rebuild = function () {
  55875. this.update();
  55876. };
  55877. /**
  55878. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  55879. */
  55880. VideoTexture.prototype.update = function () {
  55881. if (!this.autoUpdateTexture) {
  55882. // Expecting user to call `updateTexture` manually
  55883. return;
  55884. }
  55885. this.updateTexture(true);
  55886. };
  55887. /**
  55888. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  55889. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  55890. */
  55891. VideoTexture.prototype.updateTexture = function (isVisible) {
  55892. if (!isVisible) {
  55893. return;
  55894. }
  55895. if (this.video.paused) {
  55896. return;
  55897. }
  55898. this._updateInternalTexture();
  55899. };
  55900. /**
  55901. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  55902. * @param url New url.
  55903. */
  55904. VideoTexture.prototype.updateURL = function (url) {
  55905. this.video.src = url;
  55906. };
  55907. VideoTexture.prototype.dispose = function () {
  55908. _super.prototype.dispose.call(this);
  55909. this.video.removeEventListener("canplay", this._createInternalTexture);
  55910. this.video.removeEventListener("paused", this._updateInternalTexture);
  55911. this.video.removeEventListener("seeked", this._updateInternalTexture);
  55912. this.video.removeEventListener("emptied", this.reset);
  55913. };
  55914. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  55915. var video = document.createElement("video");
  55916. var constraintsDeviceId;
  55917. if (constraints && constraints.deviceId) {
  55918. constraintsDeviceId = {
  55919. exact: constraints.deviceId,
  55920. };
  55921. }
  55922. navigator.getUserMedia =
  55923. navigator.getUserMedia ||
  55924. navigator.webkitGetUserMedia ||
  55925. navigator.mozGetUserMedia ||
  55926. navigator.msGetUserMedia;
  55927. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  55928. if (navigator.getUserMedia) {
  55929. navigator.getUserMedia({
  55930. video: {
  55931. deviceId: constraintsDeviceId,
  55932. width: {
  55933. min: (constraints && constraints.minWidth) || 256,
  55934. max: (constraints && constraints.maxWidth) || 640,
  55935. },
  55936. height: {
  55937. min: (constraints && constraints.minHeight) || 256,
  55938. max: (constraints && constraints.maxHeight) || 480,
  55939. },
  55940. },
  55941. }, function (stream) {
  55942. if (video.mozSrcObject !== undefined) {
  55943. // hack for Firefox < 19
  55944. video.mozSrcObject = stream;
  55945. }
  55946. else {
  55947. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  55948. }
  55949. video.play();
  55950. if (onReady) {
  55951. onReady(new VideoTexture("video", video, scene, true, true));
  55952. }
  55953. }, function (e) {
  55954. BABYLON.Tools.Error(e.name);
  55955. });
  55956. }
  55957. };
  55958. return VideoTexture;
  55959. }(BABYLON.Texture));
  55960. BABYLON.VideoTexture = VideoTexture;
  55961. })(BABYLON || (BABYLON = {}));
  55962. //# sourceMappingURL=babylon.videoTexture.js.map
  55963. var BABYLON;
  55964. (function (BABYLON) {
  55965. var RawTexture = /** @class */ (function (_super) {
  55966. __extends(RawTexture, _super);
  55967. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  55968. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55969. if (invertY === void 0) { invertY = false; }
  55970. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55971. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55972. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55973. _this.format = format;
  55974. _this._engine = scene.getEngine();
  55975. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  55976. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55977. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55978. return _this;
  55979. }
  55980. RawTexture.prototype.update = function (data) {
  55981. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  55982. };
  55983. // Statics
  55984. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55985. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55986. if (invertY === void 0) { invertY = false; }
  55987. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55988. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  55989. };
  55990. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55991. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55992. if (invertY === void 0) { invertY = false; }
  55993. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55994. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55995. };
  55996. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55997. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55998. if (invertY === void 0) { invertY = false; }
  55999. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56000. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  56001. };
  56002. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  56003. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56004. if (invertY === void 0) { invertY = false; }
  56005. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56006. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56007. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  56008. };
  56009. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  56010. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56011. if (invertY === void 0) { invertY = false; }
  56012. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56013. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56014. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  56015. };
  56016. return RawTexture;
  56017. }(BABYLON.Texture));
  56018. BABYLON.RawTexture = RawTexture;
  56019. })(BABYLON || (BABYLON = {}));
  56020. //# sourceMappingURL=babylon.rawTexture.js.map
  56021. var BABYLON;
  56022. (function (BABYLON) {
  56023. /**
  56024. * PostProcess can be used to apply a shader to a texture after it has been rendered
  56025. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  56026. */
  56027. var PostProcess = /** @class */ (function () {
  56028. /**
  56029. * Creates a new instance of @see PostProcess
  56030. * @param name The name of the PostProcess.
  56031. * @param fragmentUrl The url of the fragment shader to be used.
  56032. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  56033. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  56034. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  56035. * @param camera The camera to apply the render pass to.
  56036. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  56037. * @param engine The engine which the post process will be applied. (default: current engine)
  56038. * @param reusable If the post process can be reused on the same frame. (default: false)
  56039. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  56040. * @param textureType Type of textures used when performing the post process. (default: 0)
  56041. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  56042. * @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
  56043. * @param blockCompilation If the shader should be compiled imediatly. (default: false)
  56044. */
  56045. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  56046. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  56047. if (defines === void 0) { defines = null; }
  56048. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56049. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  56050. if (blockCompilation === void 0) { blockCompilation = false; }
  56051. this.name = name;
  56052. /**
  56053. * Width of the texture to apply the post process on
  56054. */
  56055. this.width = -1;
  56056. /**
  56057. * Height of the texture to apply the post process on
  56058. */
  56059. this.height = -1;
  56060. /**
  56061. * If the buffer needs to be cleared before applying the post process. (default: true)
  56062. * Should be set to false if shader will overwrite all previous pixels.
  56063. */
  56064. this.autoClear = true;
  56065. /**
  56066. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  56067. */
  56068. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  56069. /**
  56070. * Animations to be used for the post processing
  56071. */
  56072. this.animations = new Array();
  56073. /**
  56074. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  56075. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  56076. */
  56077. this.enablePixelPerfectMode = false;
  56078. /**
  56079. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  56080. */
  56081. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  56082. /**
  56083. * Force textures to be a power of two (default: false)
  56084. */
  56085. this.alwaysForcePOT = false;
  56086. /**
  56087. * Number of sample textures (default: 1)
  56088. */
  56089. this.samples = 1;
  56090. /**
  56091. * Modify the scale of the post process to be the same as the viewport (default: false)
  56092. */
  56093. this.adaptScaleToCurrentViewport = false;
  56094. this._reusable = false;
  56095. /**
  56096. * Smart array of input and output textures for the post process.
  56097. */
  56098. this._textures = new BABYLON.SmartArray(2);
  56099. /**
  56100. * The index in _textures that corresponds to the output texture.
  56101. */
  56102. this._currentRenderTextureInd = 0;
  56103. this._scaleRatio = new BABYLON.Vector2(1, 1);
  56104. this._texelSize = BABYLON.Vector2.Zero();
  56105. // Events
  56106. /**
  56107. * An event triggered when the postprocess is activated.
  56108. * @type {BABYLON.Observable}
  56109. */
  56110. this.onActivateObservable = new BABYLON.Observable();
  56111. /**
  56112. * An event triggered when the postprocess changes its size.
  56113. * @type {BABYLON.Observable}
  56114. */
  56115. this.onSizeChangedObservable = new BABYLON.Observable();
  56116. /**
  56117. * An event triggered when the postprocess applies its effect.
  56118. * @type {BABYLON.Observable}
  56119. */
  56120. this.onApplyObservable = new BABYLON.Observable();
  56121. /**
  56122. * An event triggered before rendering the postprocess
  56123. * @type {BABYLON.Observable}
  56124. */
  56125. this.onBeforeRenderObservable = new BABYLON.Observable();
  56126. /**
  56127. * An event triggered after rendering the postprocess
  56128. * @type {BABYLON.Observable}
  56129. */
  56130. this.onAfterRenderObservable = new BABYLON.Observable();
  56131. if (camera != null) {
  56132. this._camera = camera;
  56133. this._scene = camera.getScene();
  56134. camera.attachPostProcess(this);
  56135. this._engine = this._scene.getEngine();
  56136. this._scene.postProcesses.push(this);
  56137. }
  56138. else if (engine) {
  56139. this._engine = engine;
  56140. this._engine.postProcesses.push(this);
  56141. }
  56142. this._options = options;
  56143. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  56144. this._reusable = reusable || false;
  56145. this._textureType = textureType;
  56146. this._samplers = samplers || [];
  56147. this._samplers.push("textureSampler");
  56148. this._fragmentUrl = fragmentUrl;
  56149. this._vertexUrl = vertexUrl;
  56150. this._parameters = parameters || [];
  56151. this._parameters.push("scale");
  56152. this._indexParameters = indexParameters;
  56153. if (!blockCompilation) {
  56154. this.updateEffect(defines);
  56155. }
  56156. }
  56157. Object.defineProperty(PostProcess.prototype, "onActivate", {
  56158. /**
  56159. * A function that is added to the onActivateObservable
  56160. */
  56161. set: function (callback) {
  56162. if (this._onActivateObserver) {
  56163. this.onActivateObservable.remove(this._onActivateObserver);
  56164. }
  56165. if (callback) {
  56166. this._onActivateObserver = this.onActivateObservable.add(callback);
  56167. }
  56168. },
  56169. enumerable: true,
  56170. configurable: true
  56171. });
  56172. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  56173. /**
  56174. * A function that is added to the onSizeChangedObservable
  56175. */
  56176. set: function (callback) {
  56177. if (this._onSizeChangedObserver) {
  56178. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  56179. }
  56180. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  56181. },
  56182. enumerable: true,
  56183. configurable: true
  56184. });
  56185. Object.defineProperty(PostProcess.prototype, "onApply", {
  56186. /**
  56187. * A function that is added to the onApplyObservable
  56188. */
  56189. set: function (callback) {
  56190. if (this._onApplyObserver) {
  56191. this.onApplyObservable.remove(this._onApplyObserver);
  56192. }
  56193. this._onApplyObserver = this.onApplyObservable.add(callback);
  56194. },
  56195. enumerable: true,
  56196. configurable: true
  56197. });
  56198. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  56199. /**
  56200. * A function that is added to the onBeforeRenderObservable
  56201. */
  56202. set: function (callback) {
  56203. if (this._onBeforeRenderObserver) {
  56204. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56205. }
  56206. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56207. },
  56208. enumerable: true,
  56209. configurable: true
  56210. });
  56211. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  56212. /**
  56213. * A function that is added to the onAfterRenderObservable
  56214. */
  56215. set: function (callback) {
  56216. if (this._onAfterRenderObserver) {
  56217. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56218. }
  56219. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56220. },
  56221. enumerable: true,
  56222. configurable: true
  56223. });
  56224. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  56225. /**
  56226. * The resulting output of the post process.
  56227. */
  56228. get: function () {
  56229. return this._textures.data[this._currentRenderTextureInd];
  56230. },
  56231. set: function (value) {
  56232. this._forcedOutputTexture = value;
  56233. },
  56234. enumerable: true,
  56235. configurable: true
  56236. });
  56237. /**
  56238. * Gets the camera which post process is applied to.
  56239. * @returns The camera the post process is applied to.
  56240. */
  56241. PostProcess.prototype.getCamera = function () {
  56242. return this._camera;
  56243. };
  56244. Object.defineProperty(PostProcess.prototype, "texelSize", {
  56245. /**
  56246. * Gets the texel size of the postprocess.
  56247. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  56248. */
  56249. get: function () {
  56250. if (this._shareOutputWithPostProcess) {
  56251. return this._shareOutputWithPostProcess.texelSize;
  56252. }
  56253. if (this._forcedOutputTexture) {
  56254. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  56255. }
  56256. return this._texelSize;
  56257. },
  56258. enumerable: true,
  56259. configurable: true
  56260. });
  56261. /**
  56262. * Gets the engine which this post process belongs to.
  56263. * @returns The engine the post process was enabled with.
  56264. */
  56265. PostProcess.prototype.getEngine = function () {
  56266. return this._engine;
  56267. };
  56268. /**
  56269. * The effect that is created when initializing the post process.
  56270. * @returns The created effect corrisponding the the postprocess.
  56271. */
  56272. PostProcess.prototype.getEffect = function () {
  56273. return this._effect;
  56274. };
  56275. /**
  56276. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  56277. * @param postProcess The post process to share the output with.
  56278. * @returns This post process.
  56279. */
  56280. PostProcess.prototype.shareOutputWith = function (postProcess) {
  56281. this._disposeTextures();
  56282. this._shareOutputWithPostProcess = postProcess;
  56283. return this;
  56284. };
  56285. /**
  56286. * Updates the effect with the current post process compile time values and recompiles the shader.
  56287. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  56288. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  56289. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  56290. * @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
  56291. * @param onCompiled Called when the shader has been compiled.
  56292. * @param onError Called if there is an error when compiling a shader.
  56293. */
  56294. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  56295. if (defines === void 0) { defines = null; }
  56296. if (uniforms === void 0) { uniforms = null; }
  56297. if (samplers === void 0) { samplers = null; }
  56298. 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);
  56299. };
  56300. /**
  56301. * The post process is reusable if it can be used multiple times within one frame.
  56302. * @returns If the post process is reusable
  56303. */
  56304. PostProcess.prototype.isReusable = function () {
  56305. return this._reusable;
  56306. };
  56307. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  56308. PostProcess.prototype.markTextureDirty = function () {
  56309. this.width = -1;
  56310. };
  56311. /**
  56312. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  56313. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  56314. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  56315. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  56316. */
  56317. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  56318. var _this = this;
  56319. if (sourceTexture === void 0) { sourceTexture = null; }
  56320. camera = camera || this._camera;
  56321. var scene = camera.getScene();
  56322. var engine = scene.getEngine();
  56323. var maxSize = engine.getCaps().maxTextureSize;
  56324. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  56325. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  56326. var desiredWidth = (this._options.width || requiredWidth);
  56327. var desiredHeight = this._options.height || requiredHeight;
  56328. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  56329. if (this.adaptScaleToCurrentViewport) {
  56330. var currentViewport = engine.currentViewport;
  56331. if (currentViewport) {
  56332. desiredWidth *= currentViewport.width;
  56333. desiredHeight *= currentViewport.height;
  56334. }
  56335. }
  56336. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  56337. if (!this._options.width) {
  56338. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  56339. }
  56340. if (!this._options.height) {
  56341. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  56342. }
  56343. }
  56344. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  56345. if (this._textures.length > 0) {
  56346. for (var i = 0; i < this._textures.length; i++) {
  56347. this._engine._releaseTexture(this._textures.data[i]);
  56348. }
  56349. this._textures.reset();
  56350. }
  56351. this.width = desiredWidth;
  56352. this.height = desiredHeight;
  56353. var textureSize = { width: this.width, height: this.height };
  56354. var textureOptions = {
  56355. generateMipMaps: false,
  56356. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  56357. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  56358. samplingMode: this.renderTargetSamplingMode,
  56359. type: this._textureType
  56360. };
  56361. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  56362. if (this._reusable) {
  56363. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  56364. }
  56365. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  56366. this.onSizeChangedObservable.notifyObservers(this);
  56367. }
  56368. this._textures.forEach(function (texture) {
  56369. if (texture.samples !== _this.samples) {
  56370. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  56371. }
  56372. });
  56373. }
  56374. var target;
  56375. if (this._shareOutputWithPostProcess) {
  56376. target = this._shareOutputWithPostProcess.outputTexture;
  56377. }
  56378. else if (this._forcedOutputTexture) {
  56379. target = this._forcedOutputTexture;
  56380. this.width = this._forcedOutputTexture.width;
  56381. this.height = this._forcedOutputTexture.height;
  56382. }
  56383. else {
  56384. target = this.outputTexture;
  56385. }
  56386. if (this.enablePixelPerfectMode) {
  56387. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  56388. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  56389. }
  56390. else {
  56391. this._scaleRatio.copyFromFloats(1, 1);
  56392. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  56393. }
  56394. this.onActivateObservable.notifyObservers(camera);
  56395. // Clear
  56396. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  56397. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  56398. }
  56399. if (this._reusable) {
  56400. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  56401. }
  56402. };
  56403. Object.defineProperty(PostProcess.prototype, "isSupported", {
  56404. /**
  56405. * If the post process is supported.
  56406. */
  56407. get: function () {
  56408. return this._effect.isSupported;
  56409. },
  56410. enumerable: true,
  56411. configurable: true
  56412. });
  56413. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  56414. /**
  56415. * The aspect ratio of the output texture.
  56416. */
  56417. get: function () {
  56418. if (this._shareOutputWithPostProcess) {
  56419. return this._shareOutputWithPostProcess.aspectRatio;
  56420. }
  56421. if (this._forcedOutputTexture) {
  56422. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  56423. }
  56424. return this.width / this.height;
  56425. },
  56426. enumerable: true,
  56427. configurable: true
  56428. });
  56429. /**
  56430. * Get a value indicating if the post-process is ready to be used
  56431. * @returns true if the post-process is ready (shader is compiled)
  56432. */
  56433. PostProcess.prototype.isReady = function () {
  56434. return this._effect && this._effect.isReady();
  56435. };
  56436. /**
  56437. * Binds all textures and uniforms to the shader, this will be run on every pass.
  56438. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  56439. */
  56440. PostProcess.prototype.apply = function () {
  56441. // Check
  56442. if (!this._effect || !this._effect.isReady())
  56443. return null;
  56444. // States
  56445. this._engine.enableEffect(this._effect);
  56446. this._engine.setState(false);
  56447. this._engine.setDepthBuffer(false);
  56448. this._engine.setDepthWrite(false);
  56449. // Alpha
  56450. this._engine.setAlphaMode(this.alphaMode);
  56451. if (this.alphaConstants) {
  56452. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  56453. }
  56454. // Texture
  56455. var source;
  56456. if (this._shareOutputWithPostProcess) {
  56457. source = this._shareOutputWithPostProcess.outputTexture;
  56458. }
  56459. else if (this._forcedOutputTexture) {
  56460. source = this._forcedOutputTexture;
  56461. }
  56462. else {
  56463. source = this.outputTexture;
  56464. }
  56465. this._effect._bindTexture("textureSampler", source);
  56466. // Parameters
  56467. this._effect.setVector2("scale", this._scaleRatio);
  56468. this.onApplyObservable.notifyObservers(this._effect);
  56469. return this._effect;
  56470. };
  56471. PostProcess.prototype._disposeTextures = function () {
  56472. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  56473. return;
  56474. }
  56475. if (this._textures.length > 0) {
  56476. for (var i = 0; i < this._textures.length; i++) {
  56477. this._engine._releaseTexture(this._textures.data[i]);
  56478. }
  56479. }
  56480. this._textures.dispose();
  56481. };
  56482. /**
  56483. * Disposes the post process.
  56484. * @param camera The camera to dispose the post process on.
  56485. */
  56486. PostProcess.prototype.dispose = function (camera) {
  56487. camera = camera || this._camera;
  56488. this._disposeTextures();
  56489. if (this._scene) {
  56490. var index_1 = this._scene.postProcesses.indexOf(this);
  56491. if (index_1 !== -1) {
  56492. this._scene.postProcesses.splice(index_1, 1);
  56493. }
  56494. }
  56495. else {
  56496. var index_2 = this._engine.postProcesses.indexOf(this);
  56497. if (index_2 !== -1) {
  56498. this._engine.postProcesses.splice(index_2, 1);
  56499. }
  56500. }
  56501. if (!camera) {
  56502. return;
  56503. }
  56504. camera.detachPostProcess(this);
  56505. var index = camera._postProcesses.indexOf(this);
  56506. if (index === 0 && camera._postProcesses.length > 0) {
  56507. this._camera._postProcesses[0].markTextureDirty();
  56508. }
  56509. this.onActivateObservable.clear();
  56510. this.onAfterRenderObservable.clear();
  56511. this.onApplyObservable.clear();
  56512. this.onBeforeRenderObservable.clear();
  56513. this.onSizeChangedObservable.clear();
  56514. };
  56515. return PostProcess;
  56516. }());
  56517. BABYLON.PostProcess = PostProcess;
  56518. })(BABYLON || (BABYLON = {}));
  56519. //# sourceMappingURL=babylon.postProcess.js.map
  56520. var BABYLON;
  56521. (function (BABYLON) {
  56522. var PassPostProcess = /** @class */ (function (_super) {
  56523. __extends(PassPostProcess, _super);
  56524. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56525. if (camera === void 0) { camera = null; }
  56526. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56527. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  56528. }
  56529. return PassPostProcess;
  56530. }(BABYLON.PostProcess));
  56531. BABYLON.PassPostProcess = PassPostProcess;
  56532. })(BABYLON || (BABYLON = {}));
  56533. //# sourceMappingURL=babylon.passPostProcess.js.map
  56534. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56535. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56536. s = arguments[i];
  56537. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56538. t[p] = s[p];
  56539. }
  56540. return t;
  56541. };
  56542. var BABYLON;
  56543. (function (BABYLON) {
  56544. /**
  56545. * Default implementation of @see IShadowGenerator.
  56546. * This is the main object responsible of generating shadows in the framework.
  56547. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  56548. */
  56549. var ShadowGenerator = /** @class */ (function () {
  56550. /**
  56551. * Creates a ShadowGenerator object.
  56552. * A ShadowGenerator is the required tool to use the shadows.
  56553. * Each light casting shadows needs to use its own ShadowGenerator.
  56554. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  56555. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  56556. * @param light The light object generating the shadows.
  56557. * @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.
  56558. */
  56559. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  56560. this._bias = 0.00005;
  56561. this._blurBoxOffset = 1;
  56562. this._blurScale = 2;
  56563. this._blurKernel = 1;
  56564. this._useKernelBlur = false;
  56565. this._filter = ShadowGenerator.FILTER_NONE;
  56566. this._darkness = 0;
  56567. this._transparencyShadow = false;
  56568. /**
  56569. * Controls the extent to which the shadows fade out at the edge of the frustum
  56570. * Used only by directionals and spots
  56571. */
  56572. this.frustumEdgeFalloff = 0;
  56573. /**
  56574. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  56575. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  56576. * It might on the other hand introduce peter panning.
  56577. */
  56578. this.forceBackFacesOnly = false;
  56579. this._lightDirection = BABYLON.Vector3.Zero();
  56580. this._viewMatrix = BABYLON.Matrix.Zero();
  56581. this._projectionMatrix = BABYLON.Matrix.Zero();
  56582. this._transformMatrix = BABYLON.Matrix.Zero();
  56583. this._currentFaceIndex = 0;
  56584. this._currentFaceIndexCache = 0;
  56585. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  56586. this._mapSize = mapSize;
  56587. this._light = light;
  56588. this._scene = light.getScene();
  56589. light._shadowGenerator = this;
  56590. // Texture type fallback from float to int if not supported.
  56591. var caps = this._scene.getEngine().getCaps();
  56592. if (!useFullFloatFirst) {
  56593. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56594. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56595. }
  56596. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56597. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56598. }
  56599. else {
  56600. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56601. }
  56602. }
  56603. else {
  56604. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56605. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56606. }
  56607. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56608. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56609. }
  56610. else {
  56611. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56612. }
  56613. }
  56614. this._initializeGenerator();
  56615. }
  56616. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  56617. /**
  56618. * Shadow generator mode None: no filtering applied.
  56619. */
  56620. get: function () {
  56621. return ShadowGenerator._FILTER_NONE;
  56622. },
  56623. enumerable: true,
  56624. configurable: true
  56625. });
  56626. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  56627. /**
  56628. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  56629. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  56630. */
  56631. get: function () {
  56632. return ShadowGenerator._FILTER_POISSONSAMPLING;
  56633. },
  56634. enumerable: true,
  56635. configurable: true
  56636. });
  56637. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  56638. /**
  56639. * Shadow generator mode ESM: Exponential Shadow Mapping.
  56640. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56641. */
  56642. get: function () {
  56643. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  56644. },
  56645. enumerable: true,
  56646. configurable: true
  56647. });
  56648. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  56649. /**
  56650. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  56651. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56652. */
  56653. get: function () {
  56654. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  56655. },
  56656. enumerable: true,
  56657. configurable: true
  56658. });
  56659. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  56660. /**
  56661. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  56662. * edge artifacts on steep falloff.
  56663. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56664. */
  56665. get: function () {
  56666. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56667. },
  56668. enumerable: true,
  56669. configurable: true
  56670. });
  56671. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  56672. /**
  56673. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  56674. * edge artifacts on steep falloff.
  56675. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56676. */
  56677. get: function () {
  56678. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56679. },
  56680. enumerable: true,
  56681. configurable: true
  56682. });
  56683. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  56684. /**
  56685. * Gets the bias: offset applied on the depth preventing acnea.
  56686. */
  56687. get: function () {
  56688. return this._bias;
  56689. },
  56690. /**
  56691. * Sets the bias: offset applied on the depth preventing acnea.
  56692. */
  56693. set: function (bias) {
  56694. this._bias = bias;
  56695. },
  56696. enumerable: true,
  56697. configurable: true
  56698. });
  56699. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  56700. /**
  56701. * Gets the blur box offset: offset applied during the blur pass.
  56702. * Only usefull if useKernelBlur = false
  56703. */
  56704. get: function () {
  56705. return this._blurBoxOffset;
  56706. },
  56707. /**
  56708. * Sets the blur box offset: offset applied during the blur pass.
  56709. * Only usefull if useKernelBlur = false
  56710. */
  56711. set: function (value) {
  56712. if (this._blurBoxOffset === value) {
  56713. return;
  56714. }
  56715. this._blurBoxOffset = value;
  56716. this._disposeBlurPostProcesses();
  56717. },
  56718. enumerable: true,
  56719. configurable: true
  56720. });
  56721. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  56722. /**
  56723. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  56724. * 2 means half of the size.
  56725. */
  56726. get: function () {
  56727. return this._blurScale;
  56728. },
  56729. /**
  56730. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  56731. * 2 means half of the size.
  56732. */
  56733. set: function (value) {
  56734. if (this._blurScale === value) {
  56735. return;
  56736. }
  56737. this._blurScale = value;
  56738. this._disposeBlurPostProcesses();
  56739. },
  56740. enumerable: true,
  56741. configurable: true
  56742. });
  56743. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  56744. /**
  56745. * Gets the blur kernel: kernel size of the blur pass.
  56746. * Only usefull if useKernelBlur = true
  56747. */
  56748. get: function () {
  56749. return this._blurKernel;
  56750. },
  56751. /**
  56752. * Sets the blur kernel: kernel size of the blur pass.
  56753. * Only usefull if useKernelBlur = true
  56754. */
  56755. set: function (value) {
  56756. if (this._blurKernel === value) {
  56757. return;
  56758. }
  56759. this._blurKernel = value;
  56760. this._disposeBlurPostProcesses();
  56761. },
  56762. enumerable: true,
  56763. configurable: true
  56764. });
  56765. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  56766. /**
  56767. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  56768. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56769. */
  56770. get: function () {
  56771. return this._useKernelBlur;
  56772. },
  56773. /**
  56774. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  56775. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56776. */
  56777. set: function (value) {
  56778. if (this._useKernelBlur === value) {
  56779. return;
  56780. }
  56781. this._useKernelBlur = value;
  56782. this._disposeBlurPostProcesses();
  56783. },
  56784. enumerable: true,
  56785. configurable: true
  56786. });
  56787. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  56788. /**
  56789. * Gets the depth scale used in ESM mode.
  56790. */
  56791. get: function () {
  56792. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  56793. },
  56794. /**
  56795. * Sets the depth scale used in ESM mode.
  56796. * This can override the scale stored on the light.
  56797. */
  56798. set: function (value) {
  56799. this._depthScale = value;
  56800. },
  56801. enumerable: true,
  56802. configurable: true
  56803. });
  56804. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  56805. /**
  56806. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  56807. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56808. */
  56809. get: function () {
  56810. return this._filter;
  56811. },
  56812. /**
  56813. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  56814. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56815. */
  56816. set: function (value) {
  56817. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  56818. if (this._light.needCube()) {
  56819. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56820. this.useExponentialShadowMap = true;
  56821. return;
  56822. }
  56823. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56824. this.useCloseExponentialShadowMap = true;
  56825. return;
  56826. }
  56827. }
  56828. if (this._filter === value) {
  56829. return;
  56830. }
  56831. this._filter = value;
  56832. this._disposeBlurPostProcesses();
  56833. this._applyFilterValues();
  56834. this._light._markMeshesAsLightDirty();
  56835. },
  56836. enumerable: true,
  56837. configurable: true
  56838. });
  56839. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  56840. /**
  56841. * Gets if the current filter is set to Poisson Sampling aka PCF.
  56842. */
  56843. get: function () {
  56844. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  56845. },
  56846. /**
  56847. * Sets the current filter to Poisson Sampling aka PCF.
  56848. */
  56849. set: function (value) {
  56850. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  56851. return;
  56852. }
  56853. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  56854. },
  56855. enumerable: true,
  56856. configurable: true
  56857. });
  56858. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  56859. /**
  56860. * Gets if the current filter is set to VSM.
  56861. * DEPRECATED. Should use useExponentialShadowMap instead.
  56862. */
  56863. get: function () {
  56864. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56865. return this.useExponentialShadowMap;
  56866. },
  56867. /**
  56868. * Sets the current filter is to VSM.
  56869. * DEPRECATED. Should use useExponentialShadowMap instead.
  56870. */
  56871. set: function (value) {
  56872. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56873. this.useExponentialShadowMap = value;
  56874. },
  56875. enumerable: true,
  56876. configurable: true
  56877. });
  56878. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  56879. /**
  56880. * Gets if the current filter is set to blurred VSM.
  56881. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56882. */
  56883. get: function () {
  56884. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56885. return this.useBlurExponentialShadowMap;
  56886. },
  56887. /**
  56888. * Sets the current filter is to blurred VSM.
  56889. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56890. */
  56891. set: function (value) {
  56892. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56893. this.useBlurExponentialShadowMap = value;
  56894. },
  56895. enumerable: true,
  56896. configurable: true
  56897. });
  56898. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  56899. /**
  56900. * Gets if the current filter is set to ESM.
  56901. */
  56902. get: function () {
  56903. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  56904. },
  56905. /**
  56906. * Sets the current filter is to ESM.
  56907. */
  56908. set: function (value) {
  56909. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  56910. return;
  56911. }
  56912. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56913. },
  56914. enumerable: true,
  56915. configurable: true
  56916. });
  56917. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  56918. /**
  56919. * Gets if the current filter is set to filtered ESM.
  56920. */
  56921. get: function () {
  56922. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  56923. },
  56924. /**
  56925. * Gets if the current filter is set to filtered ESM.
  56926. */
  56927. set: function (value) {
  56928. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56929. return;
  56930. }
  56931. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56932. },
  56933. enumerable: true,
  56934. configurable: true
  56935. });
  56936. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  56937. /**
  56938. * Gets if the current filter is set to "close ESM" (using the inverse of the
  56939. * exponential to prevent steep falloff artifacts).
  56940. */
  56941. get: function () {
  56942. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56943. },
  56944. /**
  56945. * Sets the current filter to "close ESM" (using the inverse of the
  56946. * exponential to prevent steep falloff artifacts).
  56947. */
  56948. set: function (value) {
  56949. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  56950. return;
  56951. }
  56952. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56953. },
  56954. enumerable: true,
  56955. configurable: true
  56956. });
  56957. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  56958. /**
  56959. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  56960. * exponential to prevent steep falloff artifacts).
  56961. */
  56962. get: function () {
  56963. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56964. },
  56965. /**
  56966. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  56967. * exponential to prevent steep falloff artifacts).
  56968. */
  56969. set: function (value) {
  56970. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56971. return;
  56972. }
  56973. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56974. },
  56975. enumerable: true,
  56976. configurable: true
  56977. });
  56978. /**
  56979. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  56980. * 0 means strongest and 1 would means no shadow.
  56981. * @returns the darkness.
  56982. */
  56983. ShadowGenerator.prototype.getDarkness = function () {
  56984. return this._darkness;
  56985. };
  56986. /**
  56987. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  56988. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  56989. * @returns the shadow generator allowing fluent coding.
  56990. */
  56991. ShadowGenerator.prototype.setDarkness = function (darkness) {
  56992. if (darkness >= 1.0)
  56993. this._darkness = 1.0;
  56994. else if (darkness <= 0.0)
  56995. this._darkness = 0.0;
  56996. else
  56997. this._darkness = darkness;
  56998. return this;
  56999. };
  57000. /**
  57001. * Sets the ability to have transparent shadow (boolean).
  57002. * @param transparent True if transparent else False
  57003. * @returns the shadow generator allowing fluent coding
  57004. */
  57005. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  57006. this._transparencyShadow = transparent;
  57007. return this;
  57008. };
  57009. /**
  57010. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  57011. * @returns The render target texture if present otherwise, null
  57012. */
  57013. ShadowGenerator.prototype.getShadowMap = function () {
  57014. return this._shadowMap;
  57015. };
  57016. /**
  57017. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  57018. * @returns The render target texture if the shadow map is present otherwise, null
  57019. */
  57020. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  57021. if (this._shadowMap2) {
  57022. return this._shadowMap2;
  57023. }
  57024. return this._shadowMap;
  57025. };
  57026. /**
  57027. * Helper function to add a mesh and its descendants to the list of shadow casters.
  57028. * @param mesh Mesh to add
  57029. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  57030. * @returns the Shadow Generator itself
  57031. */
  57032. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  57033. if (includeDescendants === void 0) { includeDescendants = true; }
  57034. if (!this._shadowMap) {
  57035. return this;
  57036. }
  57037. if (!this._shadowMap.renderList) {
  57038. this._shadowMap.renderList = [];
  57039. }
  57040. this._shadowMap.renderList.push(mesh);
  57041. if (includeDescendants) {
  57042. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  57043. }
  57044. return this;
  57045. var _a;
  57046. };
  57047. /**
  57048. * Helper function to remove a mesh and its descendants from the list of shadow casters
  57049. * @param mesh Mesh to remove
  57050. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  57051. * @returns the Shadow Generator itself
  57052. */
  57053. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  57054. if (includeDescendants === void 0) { includeDescendants = true; }
  57055. if (!this._shadowMap || !this._shadowMap.renderList) {
  57056. return this;
  57057. }
  57058. var index = this._shadowMap.renderList.indexOf(mesh);
  57059. if (index !== -1) {
  57060. this._shadowMap.renderList.splice(index, 1);
  57061. }
  57062. if (includeDescendants) {
  57063. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  57064. var child = _a[_i];
  57065. this.removeShadowCaster(child);
  57066. }
  57067. }
  57068. return this;
  57069. };
  57070. /**
  57071. * Returns the associated light object.
  57072. * @returns the light generating the shadow
  57073. */
  57074. ShadowGenerator.prototype.getLight = function () {
  57075. return this._light;
  57076. };
  57077. ShadowGenerator.prototype._initializeGenerator = function () {
  57078. this._light._markMeshesAsLightDirty();
  57079. this._initializeShadowMap();
  57080. };
  57081. ShadowGenerator.prototype._initializeShadowMap = function () {
  57082. var _this = this;
  57083. // Render target
  57084. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  57085. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57086. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57087. this._shadowMap.anisotropicFilteringLevel = 1;
  57088. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57089. this._shadowMap.renderParticles = false;
  57090. this._shadowMap.ignoreCameraViewport = true;
  57091. // Record Face Index before render.
  57092. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  57093. _this._currentFaceIndex = faceIndex;
  57094. });
  57095. // Custom render function.
  57096. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  57097. // Blur if required afer render.
  57098. this._shadowMap.onAfterUnbindObservable.add(function () {
  57099. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  57100. return;
  57101. }
  57102. var shadowMap = _this.getShadowMapForRendering();
  57103. if (shadowMap) {
  57104. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  57105. }
  57106. });
  57107. // Clear according to the chosen filter.
  57108. this._shadowMap.onClearObservable.add(function (engine) {
  57109. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  57110. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  57111. }
  57112. else {
  57113. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  57114. }
  57115. });
  57116. };
  57117. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  57118. var _this = this;
  57119. var engine = this._scene.getEngine();
  57120. var targetSize = this._mapSize / this.blurScale;
  57121. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  57122. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  57123. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57124. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57125. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57126. }
  57127. if (this.useKernelBlur) {
  57128. 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);
  57129. this._kernelBlurXPostprocess.width = targetSize;
  57130. this._kernelBlurXPostprocess.height = targetSize;
  57131. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  57132. effect.setTexture("textureSampler", _this._shadowMap);
  57133. });
  57134. 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);
  57135. this._kernelBlurXPostprocess.autoClear = false;
  57136. this._kernelBlurYPostprocess.autoClear = false;
  57137. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  57138. this._kernelBlurXPostprocess.packedFloat = true;
  57139. this._kernelBlurYPostprocess.packedFloat = true;
  57140. }
  57141. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  57142. }
  57143. else {
  57144. 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);
  57145. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  57146. effect.setFloat2("screenSize", targetSize, targetSize);
  57147. effect.setTexture("textureSampler", _this._shadowMap);
  57148. });
  57149. this._boxBlurPostprocess.autoClear = false;
  57150. this._blurPostProcesses = [this._boxBlurPostprocess];
  57151. }
  57152. };
  57153. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57154. var index;
  57155. var engine = this._scene.getEngine();
  57156. if (depthOnlySubMeshes.length) {
  57157. engine.setColorWrite(false);
  57158. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57159. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  57160. }
  57161. engine.setColorWrite(true);
  57162. }
  57163. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57164. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  57165. }
  57166. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57167. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  57168. }
  57169. if (this._transparencyShadow) {
  57170. for (index = 0; index < transparentSubMeshes.length; index++) {
  57171. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  57172. }
  57173. }
  57174. };
  57175. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  57176. var _this = this;
  57177. var mesh = subMesh.getRenderingMesh();
  57178. var scene = this._scene;
  57179. var engine = scene.getEngine();
  57180. var material = subMesh.getMaterial();
  57181. if (!material) {
  57182. return;
  57183. }
  57184. // Culling
  57185. engine.setState(material.backFaceCulling);
  57186. // Managing instances
  57187. var batch = mesh._getInstancesRenderList(subMesh._id);
  57188. if (batch.mustReturn) {
  57189. return;
  57190. }
  57191. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  57192. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  57193. engine.enableEffect(this._effect);
  57194. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  57195. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  57196. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  57197. this._effect.setVector3("lightPosition", this.getLight().position);
  57198. if (scene.activeCamera) {
  57199. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  57200. }
  57201. // Alpha test
  57202. if (material && material.needAlphaTesting()) {
  57203. var alphaTexture = material.getAlphaTestTexture();
  57204. if (alphaTexture) {
  57205. this._effect.setTexture("diffuseSampler", alphaTexture);
  57206. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  57207. }
  57208. }
  57209. // Bones
  57210. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57211. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  57212. }
  57213. if (this.forceBackFacesOnly) {
  57214. engine.setState(true, 0, false, true);
  57215. }
  57216. // Draw
  57217. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57218. if (this.forceBackFacesOnly) {
  57219. engine.setState(true, 0, false, false);
  57220. }
  57221. }
  57222. else {
  57223. // Need to reset refresh rate of the shadowMap
  57224. if (this._shadowMap) {
  57225. this._shadowMap.resetRefreshCounter();
  57226. }
  57227. }
  57228. };
  57229. ShadowGenerator.prototype._applyFilterValues = function () {
  57230. if (!this._shadowMap) {
  57231. return;
  57232. }
  57233. if (this.filter === ShadowGenerator.FILTER_NONE) {
  57234. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57235. }
  57236. else {
  57237. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57238. }
  57239. };
  57240. /**
  57241. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  57242. * @param onCompiled Callback triggered at the and of the effects compilation
  57243. * @param options Sets of optional options forcing the compilation with different modes
  57244. */
  57245. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  57246. var _this = this;
  57247. var localOptions = __assign({ useInstances: false }, options);
  57248. var shadowMap = this.getShadowMap();
  57249. if (!shadowMap) {
  57250. if (onCompiled) {
  57251. onCompiled(this);
  57252. }
  57253. return;
  57254. }
  57255. var renderList = shadowMap.renderList;
  57256. if (!renderList) {
  57257. if (onCompiled) {
  57258. onCompiled(this);
  57259. }
  57260. return;
  57261. }
  57262. var subMeshes = new Array();
  57263. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  57264. var mesh = renderList_1[_i];
  57265. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  57266. }
  57267. if (subMeshes.length === 0) {
  57268. if (onCompiled) {
  57269. onCompiled(this);
  57270. }
  57271. return;
  57272. }
  57273. var currentIndex = 0;
  57274. var checkReady = function () {
  57275. if (!_this._scene || !_this._scene.getEngine()) {
  57276. return;
  57277. }
  57278. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  57279. currentIndex++;
  57280. if (currentIndex >= subMeshes.length) {
  57281. if (onCompiled) {
  57282. onCompiled(_this);
  57283. }
  57284. return;
  57285. }
  57286. }
  57287. setTimeout(checkReady, 16);
  57288. };
  57289. checkReady();
  57290. };
  57291. /**
  57292. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  57293. * @param subMesh The submesh we want to render in the shadow map
  57294. * @param useInstances Defines wether will draw in the map using instances
  57295. * @returns true if ready otherwise, false
  57296. */
  57297. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  57298. var defines = [];
  57299. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  57300. defines.push("#define FLOAT");
  57301. }
  57302. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  57303. defines.push("#define ESM");
  57304. }
  57305. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57306. var mesh = subMesh.getMesh();
  57307. var material = subMesh.getMaterial();
  57308. // Alpha test
  57309. if (material && material.needAlphaTesting()) {
  57310. var alphaTexture = material.getAlphaTestTexture();
  57311. if (alphaTexture) {
  57312. defines.push("#define ALPHATEST");
  57313. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57314. attribs.push(BABYLON.VertexBuffer.UVKind);
  57315. defines.push("#define UV1");
  57316. }
  57317. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57318. if (alphaTexture.coordinatesIndex === 1) {
  57319. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57320. defines.push("#define UV2");
  57321. }
  57322. }
  57323. }
  57324. }
  57325. // Bones
  57326. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57327. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57328. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57329. if (mesh.numBoneInfluencers > 4) {
  57330. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57331. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57332. }
  57333. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57334. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57335. }
  57336. else {
  57337. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57338. }
  57339. // Instances
  57340. if (useInstances) {
  57341. defines.push("#define INSTANCES");
  57342. attribs.push("world0");
  57343. attribs.push("world1");
  57344. attribs.push("world2");
  57345. attribs.push("world3");
  57346. }
  57347. // Get correct effect
  57348. var join = defines.join("\n");
  57349. if (this._cachedDefines !== join) {
  57350. this._cachedDefines = join;
  57351. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  57352. }
  57353. if (!this._effect.isReady()) {
  57354. return false;
  57355. }
  57356. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  57357. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  57358. this._initializeBlurRTTAndPostProcesses();
  57359. }
  57360. }
  57361. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  57362. return false;
  57363. }
  57364. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  57365. return false;
  57366. }
  57367. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  57368. return false;
  57369. }
  57370. return true;
  57371. };
  57372. /**
  57373. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  57374. * @param defines Defines of the material we want to update
  57375. * @param lightIndex Index of the light in the enabled light list of the material
  57376. */
  57377. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  57378. var scene = this._scene;
  57379. var light = this._light;
  57380. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  57381. return;
  57382. }
  57383. defines["SHADOW" + lightIndex] = true;
  57384. if (this.usePoissonSampling) {
  57385. defines["SHADOWPCF" + lightIndex] = true;
  57386. }
  57387. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  57388. defines["SHADOWESM" + lightIndex] = true;
  57389. }
  57390. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  57391. defines["SHADOWCLOSEESM" + lightIndex] = true;
  57392. }
  57393. if (light.needCube()) {
  57394. defines["SHADOWCUBE" + lightIndex] = true;
  57395. }
  57396. };
  57397. /**
  57398. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  57399. * defined in the generator but impacting the effect).
  57400. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  57401. * @param effect The effect we are binfing the information for
  57402. */
  57403. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  57404. var light = this._light;
  57405. var scene = this._scene;
  57406. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  57407. return;
  57408. }
  57409. var camera = scene.activeCamera;
  57410. if (!camera) {
  57411. return;
  57412. }
  57413. var shadowMap = this.getShadowMap();
  57414. if (!shadowMap) {
  57415. return;
  57416. }
  57417. if (!light.needCube()) {
  57418. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  57419. }
  57420. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  57421. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  57422. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  57423. };
  57424. /**
  57425. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  57426. * (eq to shadow prjection matrix * light transform matrix)
  57427. * @returns The transform matrix used to create the shadow map
  57428. */
  57429. ShadowGenerator.prototype.getTransformMatrix = function () {
  57430. var scene = this._scene;
  57431. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  57432. return this._transformMatrix;
  57433. }
  57434. this._currentRenderID = scene.getRenderId();
  57435. this._currentFaceIndexCache = this._currentFaceIndex;
  57436. var lightPosition = this._light.position;
  57437. if (this._light.computeTransformedInformation()) {
  57438. lightPosition = this._light.transformedPosition;
  57439. }
  57440. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  57441. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  57442. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  57443. }
  57444. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  57445. this._cachedPosition = lightPosition.clone();
  57446. this._cachedDirection = this._lightDirection.clone();
  57447. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  57448. var shadowMap = this.getShadowMap();
  57449. if (shadowMap) {
  57450. var renderList = shadowMap.renderList;
  57451. if (renderList) {
  57452. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  57453. }
  57454. }
  57455. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  57456. }
  57457. return this._transformMatrix;
  57458. };
  57459. /**
  57460. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  57461. * Cube and 2D textures for instance.
  57462. */
  57463. ShadowGenerator.prototype.recreateShadowMap = function () {
  57464. var shadowMap = this._shadowMap;
  57465. if (!shadowMap) {
  57466. return;
  57467. }
  57468. // Track render list.
  57469. var renderList = shadowMap.renderList;
  57470. // Clean up existing data.
  57471. this._disposeRTTandPostProcesses();
  57472. // Reinitializes.
  57473. this._initializeGenerator();
  57474. // Reaffect the filter to ensure a correct fallback if necessary.
  57475. this.filter = this.filter;
  57476. // Reaffect the filter.
  57477. this._applyFilterValues();
  57478. // Reaffect Render List.
  57479. this._shadowMap.renderList = renderList;
  57480. };
  57481. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  57482. if (this._shadowMap2) {
  57483. this._shadowMap2.dispose();
  57484. this._shadowMap2 = null;
  57485. }
  57486. if (this._boxBlurPostprocess) {
  57487. this._boxBlurPostprocess.dispose();
  57488. this._boxBlurPostprocess = null;
  57489. }
  57490. if (this._kernelBlurXPostprocess) {
  57491. this._kernelBlurXPostprocess.dispose();
  57492. this._kernelBlurXPostprocess = null;
  57493. }
  57494. if (this._kernelBlurYPostprocess) {
  57495. this._kernelBlurYPostprocess.dispose();
  57496. this._kernelBlurYPostprocess = null;
  57497. }
  57498. this._blurPostProcesses = [];
  57499. };
  57500. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  57501. if (this._shadowMap) {
  57502. this._shadowMap.dispose();
  57503. this._shadowMap = null;
  57504. }
  57505. this._disposeBlurPostProcesses();
  57506. };
  57507. /**
  57508. * Disposes the ShadowGenerator.
  57509. * Returns nothing.
  57510. */
  57511. ShadowGenerator.prototype.dispose = function () {
  57512. this._disposeRTTandPostProcesses();
  57513. if (this._light) {
  57514. this._light._shadowGenerator = null;
  57515. this._light._markMeshesAsLightDirty();
  57516. }
  57517. };
  57518. /**
  57519. * Serializes the shadow generator setup to a json object.
  57520. * @returns The serialized JSON object
  57521. */
  57522. ShadowGenerator.prototype.serialize = function () {
  57523. var serializationObject = {};
  57524. var shadowMap = this.getShadowMap();
  57525. if (!shadowMap) {
  57526. return serializationObject;
  57527. }
  57528. serializationObject.lightId = this._light.id;
  57529. serializationObject.mapSize = shadowMap.getRenderSize();
  57530. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  57531. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  57532. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  57533. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  57534. serializationObject.usePoissonSampling = this.usePoissonSampling;
  57535. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  57536. serializationObject.depthScale = this.depthScale;
  57537. serializationObject.darkness = this.getDarkness();
  57538. serializationObject.blurBoxOffset = this.blurBoxOffset;
  57539. serializationObject.blurKernel = this.blurKernel;
  57540. serializationObject.blurScale = this.blurScale;
  57541. serializationObject.useKernelBlur = this.useKernelBlur;
  57542. serializationObject.transparencyShadow = this._transparencyShadow;
  57543. serializationObject.renderList = [];
  57544. if (shadowMap.renderList) {
  57545. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  57546. var mesh = shadowMap.renderList[meshIndex];
  57547. serializationObject.renderList.push(mesh.id);
  57548. }
  57549. }
  57550. return serializationObject;
  57551. };
  57552. /**
  57553. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  57554. * @param parsedShadowGenerator The JSON object to parse
  57555. * @param scene The scene to create the shadow map for
  57556. * @returns The parsed shadow generator
  57557. */
  57558. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  57559. //casting to point light, as light is missing the position attr and typescript complains.
  57560. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  57561. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  57562. var shadowMap = shadowGenerator.getShadowMap();
  57563. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  57564. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  57565. meshes.forEach(function (mesh) {
  57566. if (!shadowMap) {
  57567. return;
  57568. }
  57569. if (!shadowMap.renderList) {
  57570. shadowMap.renderList = [];
  57571. }
  57572. shadowMap.renderList.push(mesh);
  57573. });
  57574. }
  57575. if (parsedShadowGenerator.usePoissonSampling) {
  57576. shadowGenerator.usePoissonSampling = true;
  57577. }
  57578. else if (parsedShadowGenerator.useExponentialShadowMap) {
  57579. shadowGenerator.useExponentialShadowMap = true;
  57580. }
  57581. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  57582. shadowGenerator.useBlurExponentialShadowMap = true;
  57583. }
  57584. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  57585. shadowGenerator.useCloseExponentialShadowMap = true;
  57586. }
  57587. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  57588. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  57589. }
  57590. else if (parsedShadowGenerator.useVarianceShadowMap) {
  57591. shadowGenerator.useExponentialShadowMap = true;
  57592. }
  57593. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  57594. shadowGenerator.useBlurExponentialShadowMap = true;
  57595. }
  57596. if (parsedShadowGenerator.depthScale) {
  57597. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  57598. }
  57599. if (parsedShadowGenerator.blurScale) {
  57600. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  57601. }
  57602. if (parsedShadowGenerator.blurBoxOffset) {
  57603. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  57604. }
  57605. if (parsedShadowGenerator.useKernelBlur) {
  57606. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  57607. }
  57608. if (parsedShadowGenerator.blurKernel) {
  57609. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  57610. }
  57611. if (parsedShadowGenerator.bias !== undefined) {
  57612. shadowGenerator.bias = parsedShadowGenerator.bias;
  57613. }
  57614. if (parsedShadowGenerator.darkness) {
  57615. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  57616. }
  57617. if (parsedShadowGenerator.transparencyShadow) {
  57618. shadowGenerator.setTransparencyShadow(true);
  57619. }
  57620. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  57621. return shadowGenerator;
  57622. };
  57623. ShadowGenerator._FILTER_NONE = 0;
  57624. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  57625. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  57626. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  57627. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  57628. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  57629. return ShadowGenerator;
  57630. }());
  57631. BABYLON.ShadowGenerator = ShadowGenerator;
  57632. })(BABYLON || (BABYLON = {}));
  57633. //# sourceMappingURL=babylon.shadowGenerator.js.map
  57634. var BABYLON;
  57635. (function (BABYLON) {
  57636. var DefaultLoadingScreen = /** @class */ (function () {
  57637. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  57638. if (_loadingText === void 0) { _loadingText = ""; }
  57639. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  57640. var _this = this;
  57641. this._renderingCanvas = _renderingCanvas;
  57642. this._loadingText = _loadingText;
  57643. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  57644. // Resize
  57645. this._resizeLoadingUI = function () {
  57646. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  57647. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  57648. if (!_this._loadingDiv) {
  57649. return;
  57650. }
  57651. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  57652. _this._loadingDiv.style.left = canvasRect.left + "px";
  57653. _this._loadingDiv.style.top = canvasRect.top + "px";
  57654. _this._loadingDiv.style.width = canvasRect.width + "px";
  57655. _this._loadingDiv.style.height = canvasRect.height + "px";
  57656. };
  57657. }
  57658. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  57659. if (this._loadingDiv) {
  57660. // Do not add a loading screen if there is already one
  57661. return;
  57662. }
  57663. this._loadingDiv = document.createElement("div");
  57664. this._loadingDiv.id = "babylonjsLoadingDiv";
  57665. this._loadingDiv.style.opacity = "0";
  57666. this._loadingDiv.style.transition = "opacity 1.5s ease";
  57667. this._loadingDiv.style.pointerEvents = "none";
  57668. // Loading text
  57669. this._loadingTextDiv = document.createElement("div");
  57670. this._loadingTextDiv.style.position = "absolute";
  57671. this._loadingTextDiv.style.left = "0";
  57672. this._loadingTextDiv.style.top = "50%";
  57673. this._loadingTextDiv.style.marginTop = "80px";
  57674. this._loadingTextDiv.style.width = "100%";
  57675. this._loadingTextDiv.style.height = "20px";
  57676. this._loadingTextDiv.style.fontFamily = "Arial";
  57677. this._loadingTextDiv.style.fontSize = "14px";
  57678. this._loadingTextDiv.style.color = "white";
  57679. this._loadingTextDiv.style.textAlign = "center";
  57680. this._loadingTextDiv.innerHTML = "Loading";
  57681. this._loadingDiv.appendChild(this._loadingTextDiv);
  57682. //set the predefined text
  57683. this._loadingTextDiv.innerHTML = this._loadingText;
  57684. // Generating keyframes
  57685. var style = document.createElement('style');
  57686. style.type = 'text/css';
  57687. 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 }";
  57688. style.innerHTML = keyFrames;
  57689. document.getElementsByTagName('head')[0].appendChild(style);
  57690. // Loading img
  57691. var imgBack = new Image();
  57692. 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";
  57693. imgBack.style.position = "absolute";
  57694. imgBack.style.left = "50%";
  57695. imgBack.style.top = "50%";
  57696. imgBack.style.marginLeft = "-60px";
  57697. imgBack.style.marginTop = "-60px";
  57698. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  57699. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  57700. imgBack.style.transformOrigin = "50% 50%";
  57701. imgBack.style.webkitTransformOrigin = "50% 50%";
  57702. this._loadingDiv.appendChild(imgBack);
  57703. this._resizeLoadingUI();
  57704. window.addEventListener("resize", this._resizeLoadingUI);
  57705. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57706. document.body.appendChild(this._loadingDiv);
  57707. this._loadingDiv.style.opacity = "1";
  57708. };
  57709. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  57710. var _this = this;
  57711. if (!this._loadingDiv) {
  57712. return;
  57713. }
  57714. var onTransitionEnd = function () {
  57715. if (!_this._loadingDiv) {
  57716. return;
  57717. }
  57718. document.body.removeChild(_this._loadingDiv);
  57719. window.removeEventListener("resize", _this._resizeLoadingUI);
  57720. _this._loadingDiv = null;
  57721. };
  57722. this._loadingDiv.style.opacity = "0";
  57723. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  57724. };
  57725. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  57726. set: function (text) {
  57727. this._loadingText = text;
  57728. if (this._loadingTextDiv) {
  57729. this._loadingTextDiv.innerHTML = this._loadingText;
  57730. }
  57731. },
  57732. enumerable: true,
  57733. configurable: true
  57734. });
  57735. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  57736. get: function () {
  57737. return this._loadingDivBackgroundColor;
  57738. },
  57739. set: function (color) {
  57740. this._loadingDivBackgroundColor = color;
  57741. if (!this._loadingDiv) {
  57742. return;
  57743. }
  57744. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57745. },
  57746. enumerable: true,
  57747. configurable: true
  57748. });
  57749. return DefaultLoadingScreen;
  57750. }());
  57751. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  57752. })(BABYLON || (BABYLON = {}));
  57753. //# sourceMappingURL=babylon.loadingScreen.js.map
  57754. var BABYLON;
  57755. (function (BABYLON) {
  57756. var SceneLoaderProgressEvent = /** @class */ (function () {
  57757. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  57758. this.lengthComputable = lengthComputable;
  57759. this.loaded = loaded;
  57760. this.total = total;
  57761. }
  57762. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  57763. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  57764. };
  57765. return SceneLoaderProgressEvent;
  57766. }());
  57767. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  57768. var SceneLoader = /** @class */ (function () {
  57769. function SceneLoader() {
  57770. }
  57771. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  57772. get: function () {
  57773. return 0;
  57774. },
  57775. enumerable: true,
  57776. configurable: true
  57777. });
  57778. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  57779. get: function () {
  57780. return 1;
  57781. },
  57782. enumerable: true,
  57783. configurable: true
  57784. });
  57785. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  57786. get: function () {
  57787. return 2;
  57788. },
  57789. enumerable: true,
  57790. configurable: true
  57791. });
  57792. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  57793. get: function () {
  57794. return 3;
  57795. },
  57796. enumerable: true,
  57797. configurable: true
  57798. });
  57799. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  57800. get: function () {
  57801. return SceneLoader._ForceFullSceneLoadingForIncremental;
  57802. },
  57803. set: function (value) {
  57804. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  57805. },
  57806. enumerable: true,
  57807. configurable: true
  57808. });
  57809. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  57810. get: function () {
  57811. return SceneLoader._ShowLoadingScreen;
  57812. },
  57813. set: function (value) {
  57814. SceneLoader._ShowLoadingScreen = value;
  57815. },
  57816. enumerable: true,
  57817. configurable: true
  57818. });
  57819. Object.defineProperty(SceneLoader, "loggingLevel", {
  57820. get: function () {
  57821. return SceneLoader._loggingLevel;
  57822. },
  57823. set: function (value) {
  57824. SceneLoader._loggingLevel = value;
  57825. },
  57826. enumerable: true,
  57827. configurable: true
  57828. });
  57829. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  57830. get: function () {
  57831. return SceneLoader._CleanBoneMatrixWeights;
  57832. },
  57833. set: function (value) {
  57834. SceneLoader._CleanBoneMatrixWeights = value;
  57835. },
  57836. enumerable: true,
  57837. configurable: true
  57838. });
  57839. SceneLoader._getDefaultPlugin = function () {
  57840. return SceneLoader._registeredPlugins[".babylon"];
  57841. };
  57842. SceneLoader._getPluginForExtension = function (extension) {
  57843. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  57844. if (registeredPlugin) {
  57845. return registeredPlugin;
  57846. }
  57847. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  57848. return SceneLoader._getDefaultPlugin();
  57849. };
  57850. SceneLoader._getPluginForDirectLoad = function (data) {
  57851. for (var extension in SceneLoader._registeredPlugins) {
  57852. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  57853. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  57854. return SceneLoader._registeredPlugins[extension];
  57855. }
  57856. }
  57857. return SceneLoader._getDefaultPlugin();
  57858. };
  57859. SceneLoader._getPluginForFilename = function (sceneFilename) {
  57860. if (sceneFilename.name) {
  57861. sceneFilename = sceneFilename.name;
  57862. }
  57863. var queryStringPosition = sceneFilename.indexOf("?");
  57864. if (queryStringPosition !== -1) {
  57865. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  57866. }
  57867. var dotPosition = sceneFilename.lastIndexOf(".");
  57868. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  57869. return SceneLoader._getPluginForExtension(extension);
  57870. };
  57871. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  57872. SceneLoader._getDirectLoad = function (sceneFilename) {
  57873. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  57874. return sceneFilename.substr(5);
  57875. }
  57876. return null;
  57877. };
  57878. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  57879. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  57880. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  57881. var plugin;
  57882. if (registeredPlugin.plugin.createPlugin) {
  57883. plugin = registeredPlugin.plugin.createPlugin();
  57884. }
  57885. else {
  57886. plugin = registeredPlugin.plugin;
  57887. }
  57888. var useArrayBuffer = registeredPlugin.isBinary;
  57889. var database;
  57890. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  57891. var dataCallback = function (data, responseURL) {
  57892. if (scene.isDisposed) {
  57893. onError("Scene has been disposed");
  57894. return;
  57895. }
  57896. scene.database = database;
  57897. onSuccess(plugin, data, responseURL);
  57898. };
  57899. var request = null;
  57900. var pluginDisposed = false;
  57901. var onDisposeObservable = plugin.onDisposeObservable;
  57902. if (onDisposeObservable) {
  57903. onDisposeObservable.add(function () {
  57904. pluginDisposed = true;
  57905. if (request) {
  57906. request.abort();
  57907. request = null;
  57908. }
  57909. onDispose();
  57910. });
  57911. }
  57912. var manifestChecked = function () {
  57913. if (pluginDisposed) {
  57914. return;
  57915. }
  57916. var url = rootUrl + sceneFilename;
  57917. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  57918. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  57919. } : undefined, database, useArrayBuffer, function (request, exception) {
  57920. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  57921. });
  57922. };
  57923. if (directLoad) {
  57924. dataCallback(directLoad);
  57925. return plugin;
  57926. }
  57927. if (rootUrl.indexOf("file:") === -1) {
  57928. if (scene.getEngine().enableOfflineSupport) {
  57929. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  57930. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  57931. }
  57932. else {
  57933. manifestChecked();
  57934. }
  57935. }
  57936. else {
  57937. var fileOrString = sceneFilename;
  57938. if (fileOrString.name) {
  57939. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  57940. }
  57941. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  57942. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  57943. }
  57944. else {
  57945. onError("Unable to find file named " + sceneFilename);
  57946. }
  57947. }
  57948. return plugin;
  57949. };
  57950. // Public functions
  57951. SceneLoader.GetPluginForExtension = function (extension) {
  57952. return SceneLoader._getPluginForExtension(extension).plugin;
  57953. };
  57954. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  57955. return !!SceneLoader._registeredPlugins[extension];
  57956. };
  57957. SceneLoader.RegisterPlugin = function (plugin) {
  57958. if (typeof plugin.extensions === "string") {
  57959. var extension = plugin.extensions;
  57960. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57961. plugin: plugin,
  57962. isBinary: false
  57963. };
  57964. }
  57965. else {
  57966. var extensions = plugin.extensions;
  57967. Object.keys(extensions).forEach(function (extension) {
  57968. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57969. plugin: plugin,
  57970. isBinary: extensions[extension].isBinary
  57971. };
  57972. });
  57973. }
  57974. };
  57975. /**
  57976. * Import meshes into a scene
  57977. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  57978. * @param rootUrl a string that defines the root url for scene and resources
  57979. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57980. * @param scene the instance of BABYLON.Scene to append to
  57981. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  57982. * @param onProgress a callback with a progress event for each file being loaded
  57983. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57984. */
  57985. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57986. if (onSuccess === void 0) { onSuccess = null; }
  57987. if (onProgress === void 0) { onProgress = null; }
  57988. if (onError === void 0) { onError = null; }
  57989. if (pluginExtension === void 0) { pluginExtension = null; }
  57990. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57991. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57992. return null;
  57993. }
  57994. var loadingToken = {};
  57995. scene._addPendingData(loadingToken);
  57996. var disposeHandler = function () {
  57997. scene._removePendingData(loadingToken);
  57998. };
  57999. var errorHandler = function (message, exception) {
  58000. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  58001. if (onError) {
  58002. onError(scene, errorMessage, exception);
  58003. }
  58004. else {
  58005. BABYLON.Tools.Error(errorMessage);
  58006. // should the exception be thrown?
  58007. }
  58008. disposeHandler();
  58009. };
  58010. var progressHandler = onProgress ? function (event) {
  58011. try {
  58012. onProgress(event);
  58013. }
  58014. catch (e) {
  58015. errorHandler("Error in onProgress callback", e);
  58016. }
  58017. } : undefined;
  58018. var successHandler = function (meshes, particleSystems, skeletons) {
  58019. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  58020. if (onSuccess) {
  58021. try {
  58022. onSuccess(meshes, particleSystems, skeletons);
  58023. }
  58024. catch (e) {
  58025. errorHandler("Error in onSuccess callback", e);
  58026. }
  58027. }
  58028. scene._removePendingData(loadingToken);
  58029. };
  58030. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  58031. if (plugin.rewriteRootURL) {
  58032. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  58033. }
  58034. if (sceneFilename === "") {
  58035. if (sceneFilename === "") {
  58036. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  58037. }
  58038. }
  58039. if (plugin.importMesh) {
  58040. var syncedPlugin = plugin;
  58041. var meshes = new Array();
  58042. var particleSystems = new Array();
  58043. var skeletons = new Array();
  58044. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  58045. return;
  58046. }
  58047. scene.loadingPluginName = plugin.name;
  58048. successHandler(meshes, particleSystems, skeletons);
  58049. }
  58050. else {
  58051. var asyncedPlugin = plugin;
  58052. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  58053. scene.loadingPluginName = plugin.name;
  58054. successHandler(meshes, particleSystems, skeletons);
  58055. }, progressHandler, errorHandler);
  58056. }
  58057. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  58058. };
  58059. /**
  58060. * Load a scene
  58061. * @param rootUrl a string that defines the root url for scene and resources
  58062. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  58063. * @param engine is the instance of BABYLON.Engine to use to create the scene
  58064. * @param onSuccess a callback with the scene when import succeeds
  58065. * @param onProgress a callback with a progress event for each file being loaded
  58066. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  58067. */
  58068. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  58069. if (onSuccess === void 0) { onSuccess = null; }
  58070. if (onProgress === void 0) { onProgress = null; }
  58071. if (onError === void 0) { onError = null; }
  58072. if (pluginExtension === void 0) { pluginExtension = null; }
  58073. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  58074. };
  58075. /**
  58076. * Append a scene
  58077. * @param rootUrl a string that defines the root url for scene and resources
  58078. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  58079. * @param scene is the instance of BABYLON.Scene to append to
  58080. * @param onSuccess a callback with the scene when import succeeds
  58081. * @param onProgress a callback with a progress event for each file being loaded
  58082. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  58083. */
  58084. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  58085. if (onSuccess === void 0) { onSuccess = null; }
  58086. if (onProgress === void 0) { onProgress = null; }
  58087. if (onError === void 0) { onError = null; }
  58088. if (pluginExtension === void 0) { pluginExtension = null; }
  58089. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  58090. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  58091. return null;
  58092. }
  58093. if (SceneLoader.ShowLoadingScreen) {
  58094. scene.getEngine().displayLoadingUI();
  58095. }
  58096. var loadingToken = {};
  58097. scene._addPendingData(loadingToken);
  58098. var disposeHandler = function () {
  58099. scene._removePendingData(loadingToken);
  58100. scene.getEngine().hideLoadingUI();
  58101. };
  58102. var errorHandler = function (message, exception) {
  58103. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  58104. if (onError) {
  58105. onError(scene, errorMessage, exception);
  58106. }
  58107. else {
  58108. BABYLON.Tools.Error(errorMessage);
  58109. // should the exception be thrown?
  58110. }
  58111. disposeHandler();
  58112. };
  58113. var progressHandler = onProgress ? function (event) {
  58114. try {
  58115. onProgress(event);
  58116. }
  58117. catch (e) {
  58118. errorHandler("Error in onProgress callback", e);
  58119. }
  58120. } : undefined;
  58121. var successHandler = function () {
  58122. if (onSuccess) {
  58123. try {
  58124. onSuccess(scene);
  58125. }
  58126. catch (e) {
  58127. errorHandler("Error in onSuccess callback", e);
  58128. }
  58129. }
  58130. scene._removePendingData(loadingToken);
  58131. };
  58132. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  58133. if (sceneFilename === "") {
  58134. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  58135. }
  58136. if (plugin.load) {
  58137. var syncedPlugin = plugin;
  58138. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  58139. return;
  58140. }
  58141. scene.loadingPluginName = plugin.name;
  58142. successHandler();
  58143. }
  58144. else {
  58145. var asyncedPlugin = plugin;
  58146. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  58147. scene.loadingPluginName = plugin.name;
  58148. successHandler();
  58149. }, progressHandler, errorHandler);
  58150. }
  58151. if (SceneLoader.ShowLoadingScreen) {
  58152. scene.executeWhenReady(function () {
  58153. scene.getEngine().hideLoadingUI();
  58154. });
  58155. }
  58156. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  58157. };
  58158. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  58159. if (onSuccess === void 0) { onSuccess = null; }
  58160. if (onProgress === void 0) { onProgress = null; }
  58161. if (onError === void 0) { onError = null; }
  58162. if (pluginExtension === void 0) { pluginExtension = null; }
  58163. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  58164. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  58165. return null;
  58166. }
  58167. var loadingToken = {};
  58168. scene._addPendingData(loadingToken);
  58169. var disposeHandler = function () {
  58170. scene._removePendingData(loadingToken);
  58171. };
  58172. var errorHandler = function (message, exception) {
  58173. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  58174. if (onError) {
  58175. onError(scene, errorMessage, exception);
  58176. }
  58177. else {
  58178. BABYLON.Tools.Error(errorMessage);
  58179. // should the exception be thrown?
  58180. }
  58181. disposeHandler();
  58182. };
  58183. var progressHandler = onProgress ? function (event) {
  58184. try {
  58185. onProgress(event);
  58186. }
  58187. catch (e) {
  58188. errorHandler("Error in onProgress callback", e);
  58189. }
  58190. } : undefined;
  58191. var successHandler = function (assets) {
  58192. if (onSuccess) {
  58193. try {
  58194. onSuccess(assets);
  58195. }
  58196. catch (e) {
  58197. errorHandler("Error in onSuccess callback", e);
  58198. }
  58199. }
  58200. scene._removePendingData(loadingToken);
  58201. };
  58202. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  58203. if (plugin.loadAssets) {
  58204. var syncedPlugin = plugin;
  58205. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  58206. if (!assetContainer) {
  58207. return;
  58208. }
  58209. scene.loadingPluginName = plugin.name;
  58210. successHandler(assetContainer);
  58211. }
  58212. else if (plugin.loadAssetsAsync) {
  58213. var asyncedPlugin = plugin;
  58214. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  58215. if (assetContainer) {
  58216. scene.loadingPluginName = plugin.name;
  58217. successHandler(assetContainer);
  58218. }
  58219. }, progressHandler, errorHandler);
  58220. }
  58221. else {
  58222. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  58223. }
  58224. if (SceneLoader.ShowLoadingScreen) {
  58225. scene.executeWhenReady(function () {
  58226. scene.getEngine().hideLoadingUI();
  58227. });
  58228. }
  58229. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  58230. };
  58231. // Flags
  58232. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  58233. SceneLoader._ShowLoadingScreen = true;
  58234. SceneLoader._CleanBoneMatrixWeights = false;
  58235. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  58236. // Members
  58237. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  58238. SceneLoader._registeredPlugins = {};
  58239. return SceneLoader;
  58240. }());
  58241. BABYLON.SceneLoader = SceneLoader;
  58242. ;
  58243. })(BABYLON || (BABYLON = {}));
  58244. //# sourceMappingURL=babylon.sceneLoader.js.map
  58245. var BABYLON;
  58246. (function (BABYLON) {
  58247. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  58248. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  58249. var parsedMaterial = parsedData.materials[index];
  58250. if (parsedMaterial.id === id) {
  58251. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  58252. }
  58253. }
  58254. return null;
  58255. };
  58256. var isDescendantOf = function (mesh, names, hierarchyIds) {
  58257. for (var i in names) {
  58258. if (mesh.name === names[i]) {
  58259. hierarchyIds.push(mesh.id);
  58260. return true;
  58261. }
  58262. }
  58263. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  58264. hierarchyIds.push(mesh.id);
  58265. return true;
  58266. }
  58267. return false;
  58268. };
  58269. var logOperation = function (operation, producer) {
  58270. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  58271. };
  58272. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  58273. if (addToScene === void 0) { addToScene = false; }
  58274. var container = new BABYLON.AssetContainer(scene);
  58275. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58276. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58277. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58278. // and avoid problems with multiple concurrent .babylon loads.
  58279. var log = "importScene has failed JSON parse";
  58280. try {
  58281. var parsedData = JSON.parse(data);
  58282. log = "";
  58283. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  58284. var index;
  58285. var cache;
  58286. // Lights
  58287. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  58288. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  58289. var parsedLight = parsedData.lights[index];
  58290. var light = BABYLON.Light.Parse(parsedLight, scene);
  58291. if (light) {
  58292. container.lights.push(light);
  58293. log += (index === 0 ? "\n\tLights:" : "");
  58294. log += "\n\t\t" + light.toString(fullDetails);
  58295. }
  58296. }
  58297. }
  58298. // Animations
  58299. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  58300. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  58301. var parsedAnimation = parsedData.animations[index];
  58302. var animation = BABYLON.Animation.Parse(parsedAnimation);
  58303. scene.animations.push(animation);
  58304. container.animations.push(animation);
  58305. log += (index === 0 ? "\n\tAnimations:" : "");
  58306. log += "\n\t\t" + animation.toString(fullDetails);
  58307. }
  58308. }
  58309. // Materials
  58310. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  58311. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  58312. var parsedMaterial = parsedData.materials[index];
  58313. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  58314. container.materials.push(mat);
  58315. log += (index === 0 ? "\n\tMaterials:" : "");
  58316. log += "\n\t\t" + mat.toString(fullDetails);
  58317. }
  58318. }
  58319. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  58320. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  58321. var parsedMultiMaterial = parsedData.multiMaterials[index];
  58322. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  58323. container.multiMaterials.push(mmat);
  58324. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  58325. log += "\n\t\t" + mmat.toString(fullDetails);
  58326. }
  58327. }
  58328. // Morph targets
  58329. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  58330. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  58331. var managerData = _a[_i];
  58332. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  58333. }
  58334. }
  58335. // Skeletons
  58336. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  58337. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  58338. var parsedSkeleton = parsedData.skeletons[index];
  58339. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  58340. container.skeletons.push(skeleton);
  58341. log += (index === 0 ? "\n\tSkeletons:" : "");
  58342. log += "\n\t\t" + skeleton.toString(fullDetails);
  58343. }
  58344. }
  58345. // Geometries
  58346. var geometries = parsedData.geometries;
  58347. if (geometries !== undefined && geometries !== null) {
  58348. var addedGeometry = new Array();
  58349. // Boxes
  58350. var boxes = geometries.boxes;
  58351. if (boxes !== undefined && boxes !== null) {
  58352. for (index = 0, cache = boxes.length; index < cache; index++) {
  58353. var parsedBox = boxes[index];
  58354. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  58355. }
  58356. }
  58357. // Spheres
  58358. var spheres = geometries.spheres;
  58359. if (spheres !== undefined && spheres !== null) {
  58360. for (index = 0, cache = spheres.length; index < cache; index++) {
  58361. var parsedSphere = spheres[index];
  58362. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  58363. }
  58364. }
  58365. // Cylinders
  58366. var cylinders = geometries.cylinders;
  58367. if (cylinders !== undefined && cylinders !== null) {
  58368. for (index = 0, cache = cylinders.length; index < cache; index++) {
  58369. var parsedCylinder = cylinders[index];
  58370. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  58371. }
  58372. }
  58373. // Toruses
  58374. var toruses = geometries.toruses;
  58375. if (toruses !== undefined && toruses !== null) {
  58376. for (index = 0, cache = toruses.length; index < cache; index++) {
  58377. var parsedTorus = toruses[index];
  58378. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  58379. }
  58380. }
  58381. // Grounds
  58382. var grounds = geometries.grounds;
  58383. if (grounds !== undefined && grounds !== null) {
  58384. for (index = 0, cache = grounds.length; index < cache; index++) {
  58385. var parsedGround = grounds[index];
  58386. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  58387. }
  58388. }
  58389. // Planes
  58390. var planes = geometries.planes;
  58391. if (planes !== undefined && planes !== null) {
  58392. for (index = 0, cache = planes.length; index < cache; index++) {
  58393. var parsedPlane = planes[index];
  58394. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  58395. }
  58396. }
  58397. // TorusKnots
  58398. var torusKnots = geometries.torusKnots;
  58399. if (torusKnots !== undefined && torusKnots !== null) {
  58400. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  58401. var parsedTorusKnot = torusKnots[index];
  58402. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  58403. }
  58404. }
  58405. // VertexData
  58406. var vertexData = geometries.vertexData;
  58407. if (vertexData !== undefined && vertexData !== null) {
  58408. for (index = 0, cache = vertexData.length; index < cache; index++) {
  58409. var parsedVertexData = vertexData[index];
  58410. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  58411. }
  58412. }
  58413. addedGeometry.forEach(function (g) {
  58414. if (g) {
  58415. container.geometries.push(g);
  58416. }
  58417. });
  58418. }
  58419. // Transform nodes
  58420. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  58421. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  58422. var parsedTransformNode = parsedData.transformNodes[index];
  58423. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  58424. container.transformNodes.push(node);
  58425. }
  58426. }
  58427. // Meshes
  58428. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  58429. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  58430. var parsedMesh = parsedData.meshes[index];
  58431. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  58432. container.meshes.push(mesh);
  58433. log += (index === 0 ? "\n\tMeshes:" : "");
  58434. log += "\n\t\t" + mesh.toString(fullDetails);
  58435. }
  58436. }
  58437. // Cameras
  58438. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  58439. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  58440. var parsedCamera = parsedData.cameras[index];
  58441. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  58442. container.cameras.push(camera);
  58443. log += (index === 0 ? "\n\tCameras:" : "");
  58444. log += "\n\t\t" + camera.toString(fullDetails);
  58445. }
  58446. }
  58447. // Browsing all the graph to connect the dots
  58448. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  58449. var camera = scene.cameras[index];
  58450. if (camera._waitingParentId) {
  58451. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  58452. camera._waitingParentId = null;
  58453. }
  58454. }
  58455. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  58456. var light_1 = scene.lights[index];
  58457. if (light_1 && light_1._waitingParentId) {
  58458. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  58459. light_1._waitingParentId = null;
  58460. }
  58461. }
  58462. // Sounds
  58463. // TODO: add sound
  58464. var loadedSounds = [];
  58465. var loadedSound;
  58466. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  58467. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  58468. var parsedSound = parsedData.sounds[index];
  58469. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58470. if (!parsedSound.url)
  58471. parsedSound.url = parsedSound.name;
  58472. if (!loadedSounds[parsedSound.url]) {
  58473. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  58474. loadedSounds[parsedSound.url] = loadedSound;
  58475. container.sounds.push(loadedSound);
  58476. }
  58477. else {
  58478. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  58479. }
  58480. }
  58481. else {
  58482. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  58483. }
  58484. }
  58485. }
  58486. loadedSounds = [];
  58487. // Connect parents & children and parse actions
  58488. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  58489. var transformNode = scene.transformNodes[index];
  58490. if (transformNode._waitingParentId) {
  58491. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  58492. transformNode._waitingParentId = null;
  58493. }
  58494. }
  58495. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58496. var mesh = scene.meshes[index];
  58497. if (mesh._waitingParentId) {
  58498. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  58499. mesh._waitingParentId = null;
  58500. }
  58501. if (mesh._waitingActions) {
  58502. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  58503. mesh._waitingActions = null;
  58504. }
  58505. }
  58506. // freeze world matrix application
  58507. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58508. var currentMesh = scene.meshes[index];
  58509. if (currentMesh._waitingFreezeWorldMatrix) {
  58510. currentMesh.freezeWorldMatrix();
  58511. currentMesh._waitingFreezeWorldMatrix = null;
  58512. }
  58513. else {
  58514. currentMesh.computeWorldMatrix(true);
  58515. }
  58516. }
  58517. // Particles Systems
  58518. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58519. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58520. var parsedParticleSystem = parsedData.particleSystems[index];
  58521. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58522. container.particleSystems.push(ps);
  58523. }
  58524. }
  58525. // Lens flares
  58526. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  58527. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  58528. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  58529. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  58530. container.lensFlareSystems.push(lf);
  58531. }
  58532. }
  58533. // Shadows
  58534. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  58535. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  58536. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  58537. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  58538. container.shadowGenerators.push(sg);
  58539. }
  58540. }
  58541. // Lights exclusions / inclusions
  58542. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  58543. var light_2 = scene.lights[index];
  58544. // Excluded check
  58545. if (light_2._excludedMeshesIds.length > 0) {
  58546. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  58547. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  58548. if (excludedMesh) {
  58549. light_2.excludedMeshes.push(excludedMesh);
  58550. }
  58551. }
  58552. light_2._excludedMeshesIds = [];
  58553. }
  58554. // Included check
  58555. if (light_2._includedOnlyMeshesIds.length > 0) {
  58556. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  58557. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  58558. if (includedOnlyMesh) {
  58559. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  58560. }
  58561. }
  58562. light_2._includedOnlyMeshesIds = [];
  58563. }
  58564. }
  58565. // Actions (scene)
  58566. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  58567. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  58568. }
  58569. if (!addToScene) {
  58570. container.removeAllFromScene();
  58571. }
  58572. return container;
  58573. }
  58574. catch (err) {
  58575. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  58576. if (onError) {
  58577. onError(msg, err);
  58578. }
  58579. else {
  58580. BABYLON.Tools.Log(msg);
  58581. throw err;
  58582. }
  58583. }
  58584. finally {
  58585. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58586. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58587. }
  58588. }
  58589. return null;
  58590. };
  58591. BABYLON.SceneLoader.RegisterPlugin({
  58592. name: "babylon.js",
  58593. extensions: ".babylon",
  58594. canDirectLoad: function (data) {
  58595. if (data.indexOf("babylon") !== -1) {
  58596. return true;
  58597. }
  58598. return false;
  58599. },
  58600. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  58601. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58602. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58603. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58604. // and avoid problems with multiple concurrent .babylon loads.
  58605. var log = "importMesh has failed JSON parse";
  58606. try {
  58607. var parsedData = JSON.parse(data);
  58608. log = "";
  58609. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  58610. if (!meshesNames) {
  58611. meshesNames = null;
  58612. }
  58613. else if (!Array.isArray(meshesNames)) {
  58614. meshesNames = [meshesNames];
  58615. }
  58616. var hierarchyIds = new Array();
  58617. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  58618. var loadedSkeletonsIds = [];
  58619. var loadedMaterialsIds = [];
  58620. var index;
  58621. var cache;
  58622. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  58623. var parsedMesh = parsedData.meshes[index];
  58624. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  58625. if (meshesNames !== null) {
  58626. // Remove found mesh name from list.
  58627. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  58628. }
  58629. //Geometry?
  58630. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  58631. //does the file contain geometries?
  58632. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  58633. //find the correct geometry and add it to the scene
  58634. var found = false;
  58635. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  58636. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  58637. return;
  58638. }
  58639. else {
  58640. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  58641. if (parsedGeometryData.id === parsedMesh.geometryId) {
  58642. switch (geometryType) {
  58643. case "boxes":
  58644. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  58645. break;
  58646. case "spheres":
  58647. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  58648. break;
  58649. case "cylinders":
  58650. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  58651. break;
  58652. case "toruses":
  58653. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  58654. break;
  58655. case "grounds":
  58656. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  58657. break;
  58658. case "planes":
  58659. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  58660. break;
  58661. case "torusKnots":
  58662. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  58663. break;
  58664. case "vertexData":
  58665. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  58666. break;
  58667. }
  58668. found = true;
  58669. }
  58670. });
  58671. }
  58672. });
  58673. if (found === false) {
  58674. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  58675. }
  58676. }
  58677. }
  58678. // Material ?
  58679. if (parsedMesh.materialId) {
  58680. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  58681. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  58682. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  58683. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  58684. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  58685. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  58686. var subMatId = parsedMultiMaterial.materials[matIndex];
  58687. loadedMaterialsIds.push(subMatId);
  58688. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  58689. log += "\n\tMaterial " + mat.toString(fullDetails);
  58690. }
  58691. loadedMaterialsIds.push(parsedMultiMaterial.id);
  58692. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  58693. materialFound = true;
  58694. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  58695. break;
  58696. }
  58697. }
  58698. }
  58699. if (materialFound === false) {
  58700. loadedMaterialsIds.push(parsedMesh.materialId);
  58701. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  58702. if (!mat) {
  58703. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  58704. }
  58705. else {
  58706. log += "\n\tMaterial " + mat.toString(fullDetails);
  58707. }
  58708. }
  58709. }
  58710. // Skeleton ?
  58711. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  58712. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  58713. if (skeletonAlreadyLoaded === false) {
  58714. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  58715. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  58716. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  58717. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  58718. skeletons.push(skeleton);
  58719. loadedSkeletonsIds.push(parsedSkeleton.id);
  58720. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  58721. }
  58722. }
  58723. }
  58724. }
  58725. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  58726. meshes.push(mesh);
  58727. log += "\n\tMesh " + mesh.toString(fullDetails);
  58728. }
  58729. }
  58730. // Connecting parents
  58731. var currentMesh;
  58732. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58733. currentMesh = scene.meshes[index];
  58734. if (currentMesh._waitingParentId) {
  58735. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  58736. currentMesh._waitingParentId = null;
  58737. }
  58738. }
  58739. // freeze and compute world matrix application
  58740. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58741. currentMesh = scene.meshes[index];
  58742. if (currentMesh._waitingFreezeWorldMatrix) {
  58743. currentMesh.freezeWorldMatrix();
  58744. currentMesh._waitingFreezeWorldMatrix = null;
  58745. }
  58746. else {
  58747. currentMesh.computeWorldMatrix(true);
  58748. }
  58749. }
  58750. }
  58751. // Particles
  58752. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58753. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58754. var parsedParticleSystem = parsedData.particleSystems[index];
  58755. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  58756. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  58757. }
  58758. }
  58759. }
  58760. return true;
  58761. }
  58762. catch (err) {
  58763. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  58764. if (onError) {
  58765. onError(msg, err);
  58766. }
  58767. else {
  58768. BABYLON.Tools.Log(msg);
  58769. throw err;
  58770. }
  58771. }
  58772. finally {
  58773. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58774. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58775. }
  58776. }
  58777. return false;
  58778. },
  58779. load: function (scene, data, rootUrl, onError) {
  58780. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58781. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58782. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58783. // and avoid problems with multiple concurrent .babylon loads.
  58784. var log = "importScene has failed JSON parse";
  58785. try {
  58786. var parsedData = JSON.parse(data);
  58787. log = "";
  58788. // Scene
  58789. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  58790. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  58791. }
  58792. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  58793. scene.autoClear = parsedData.autoClear;
  58794. }
  58795. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  58796. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  58797. }
  58798. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  58799. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  58800. }
  58801. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  58802. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  58803. }
  58804. // Fog
  58805. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  58806. scene.fogMode = parsedData.fogMode;
  58807. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  58808. scene.fogStart = parsedData.fogStart;
  58809. scene.fogEnd = parsedData.fogEnd;
  58810. scene.fogDensity = parsedData.fogDensity;
  58811. log += "\tFog mode for scene: ";
  58812. switch (scene.fogMode) {
  58813. // getters not compiling, so using hardcoded
  58814. case 1:
  58815. log += "exp\n";
  58816. break;
  58817. case 2:
  58818. log += "exp2\n";
  58819. break;
  58820. case 3:
  58821. log += "linear\n";
  58822. break;
  58823. }
  58824. }
  58825. //Physics
  58826. if (parsedData.physicsEnabled) {
  58827. var physicsPlugin;
  58828. if (parsedData.physicsEngine === "cannon") {
  58829. physicsPlugin = new BABYLON.CannonJSPlugin();
  58830. }
  58831. else if (parsedData.physicsEngine === "oimo") {
  58832. physicsPlugin = new BABYLON.OimoJSPlugin();
  58833. }
  58834. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  58835. //else - default engine, which is currently oimo
  58836. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  58837. scene.enablePhysics(physicsGravity, physicsPlugin);
  58838. }
  58839. // Metadata
  58840. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  58841. scene.metadata = parsedData.metadata;
  58842. }
  58843. //collisions, if defined. otherwise, default is true
  58844. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  58845. scene.collisionsEnabled = parsedData.collisionsEnabled;
  58846. }
  58847. scene.workerCollisions = !!parsedData.workerCollisions;
  58848. var container = loadAssets(scene, data, rootUrl, onerror, true);
  58849. if (!container) {
  58850. return false;
  58851. }
  58852. if (parsedData.autoAnimate) {
  58853. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  58854. }
  58855. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  58856. scene.setActiveCameraByID(parsedData.activeCameraID);
  58857. }
  58858. // Environment texture
  58859. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  58860. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  58861. if (parsedData.createDefaultSkybox === true) {
  58862. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  58863. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  58864. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  58865. }
  58866. }
  58867. // Finish
  58868. return true;
  58869. }
  58870. catch (err) {
  58871. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  58872. if (onError) {
  58873. onError(msg, err);
  58874. }
  58875. else {
  58876. BABYLON.Tools.Log(msg);
  58877. throw err;
  58878. }
  58879. }
  58880. finally {
  58881. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58882. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58883. }
  58884. }
  58885. return false;
  58886. },
  58887. loadAssets: function (scene, data, rootUrl, onError) {
  58888. var container = loadAssets(scene, data, rootUrl, onerror);
  58889. return container;
  58890. }
  58891. });
  58892. })(BABYLON || (BABYLON = {}));
  58893. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  58894. var BABYLON;
  58895. (function (BABYLON) {
  58896. var FilesInput = /** @class */ (function () {
  58897. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  58898. this.onProcessFileCallback = function () { return true; };
  58899. this._engine = engine;
  58900. this._currentScene = scene;
  58901. this._sceneLoadedCallback = sceneLoadedCallback;
  58902. this._progressCallback = progressCallback;
  58903. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  58904. this._textureLoadingCallback = textureLoadingCallback;
  58905. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  58906. this._onReloadCallback = onReloadCallback;
  58907. this._errorCallback = errorCallback;
  58908. }
  58909. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  58910. var _this = this;
  58911. if (elementToMonitor) {
  58912. this._elementToMonitor = elementToMonitor;
  58913. this._dragEnterHandler = function (e) { _this.drag(e); };
  58914. this._dragOverHandler = function (e) { _this.drag(e); };
  58915. this._dropHandler = function (e) { _this.drop(e); };
  58916. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  58917. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  58918. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  58919. }
  58920. };
  58921. FilesInput.prototype.dispose = function () {
  58922. if (!this._elementToMonitor) {
  58923. return;
  58924. }
  58925. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  58926. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  58927. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  58928. };
  58929. FilesInput.prototype.renderFunction = function () {
  58930. if (this._additionalRenderLoopLogicCallback) {
  58931. this._additionalRenderLoopLogicCallback();
  58932. }
  58933. if (this._currentScene) {
  58934. if (this._textureLoadingCallback) {
  58935. var remaining = this._currentScene.getWaitingItemsCount();
  58936. if (remaining > 0) {
  58937. this._textureLoadingCallback(remaining);
  58938. }
  58939. }
  58940. this._currentScene.render();
  58941. }
  58942. };
  58943. FilesInput.prototype.drag = function (e) {
  58944. e.stopPropagation();
  58945. e.preventDefault();
  58946. };
  58947. FilesInput.prototype.drop = function (eventDrop) {
  58948. eventDrop.stopPropagation();
  58949. eventDrop.preventDefault();
  58950. this.loadFiles(eventDrop);
  58951. };
  58952. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  58953. var _this = this;
  58954. var reader = folder.createReader();
  58955. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  58956. reader.readEntries(function (entries) {
  58957. remaining.count += entries.length;
  58958. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  58959. var entry = entries_1[_i];
  58960. if (entry.isFile) {
  58961. entry.file(function (file) {
  58962. file.correctName = relativePath + file.name;
  58963. files.push(file);
  58964. if (--remaining.count === 0) {
  58965. callback();
  58966. }
  58967. });
  58968. }
  58969. else if (entry.isDirectory) {
  58970. _this._traverseFolder(entry, files, remaining, callback);
  58971. }
  58972. }
  58973. if (--remaining.count) {
  58974. callback();
  58975. }
  58976. });
  58977. };
  58978. FilesInput.prototype._processFiles = function (files) {
  58979. for (var i = 0; i < files.length; i++) {
  58980. var name = files[i].correctName.toLowerCase();
  58981. var extension = name.split('.').pop();
  58982. if (!this.onProcessFileCallback(files[i], name, extension)) {
  58983. continue;
  58984. }
  58985. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  58986. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  58987. this._sceneFileToLoad = files[i];
  58988. }
  58989. else {
  58990. FilesInput.FilesToLoad[name] = files[i];
  58991. }
  58992. }
  58993. };
  58994. FilesInput.prototype.loadFiles = function (event) {
  58995. var _this = this;
  58996. if (this._startingProcessingFilesCallback)
  58997. this._startingProcessingFilesCallback();
  58998. // Handling data transfer via drag'n'drop
  58999. if (event && event.dataTransfer && event.dataTransfer.files) {
  59000. this._filesToLoad = event.dataTransfer.files;
  59001. }
  59002. // Handling files from input files
  59003. if (event && event.target && event.target.files) {
  59004. this._filesToLoad = event.target.files;
  59005. }
  59006. if (this._filesToLoad && this._filesToLoad.length > 0) {
  59007. var files_1 = new Array();
  59008. var folders = [];
  59009. var items = event.dataTransfer ? event.dataTransfer.items : null;
  59010. for (var i = 0; i < this._filesToLoad.length; i++) {
  59011. var fileToLoad = this._filesToLoad[i];
  59012. var name_1 = fileToLoad.name.toLowerCase();
  59013. var entry = void 0;
  59014. fileToLoad.correctName = name_1;
  59015. if (items) {
  59016. var item = items[i];
  59017. if (item.getAsEntry) {
  59018. entry = item.getAsEntry();
  59019. }
  59020. else if (item.webkitGetAsEntry) {
  59021. entry = item.webkitGetAsEntry();
  59022. }
  59023. }
  59024. if (!entry) {
  59025. files_1.push(fileToLoad);
  59026. }
  59027. else {
  59028. if (entry.isDirectory) {
  59029. folders.push(entry);
  59030. }
  59031. else {
  59032. files_1.push(fileToLoad);
  59033. }
  59034. }
  59035. }
  59036. if (folders.length === 0) {
  59037. this._processFiles(files_1);
  59038. this._processReload();
  59039. }
  59040. else {
  59041. var remaining = { count: folders.length };
  59042. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  59043. var folder = folders_1[_i];
  59044. this._traverseFolder(folder, files_1, remaining, function () {
  59045. _this._processFiles(files_1);
  59046. if (remaining.count === 0) {
  59047. _this._processReload();
  59048. }
  59049. });
  59050. }
  59051. }
  59052. }
  59053. };
  59054. FilesInput.prototype._processReload = function () {
  59055. if (this._onReloadCallback) {
  59056. this._onReloadCallback(this._sceneFileToLoad);
  59057. }
  59058. else {
  59059. this.reload();
  59060. }
  59061. };
  59062. FilesInput.prototype.reload = function () {
  59063. var _this = this;
  59064. // If a scene file has been provided
  59065. if (this._sceneFileToLoad) {
  59066. if (this._currentScene) {
  59067. if (BABYLON.Tools.errorsCount > 0) {
  59068. BABYLON.Tools.ClearLogCache();
  59069. }
  59070. this._engine.stopRenderLoop();
  59071. this._currentScene.dispose();
  59072. }
  59073. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  59074. _this._currentScene = newScene;
  59075. if (_this._sceneLoadedCallback) {
  59076. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  59077. }
  59078. // Wait for textures and shaders to be ready
  59079. _this._currentScene.executeWhenReady(function () {
  59080. _this._engine.runRenderLoop(function () {
  59081. _this.renderFunction();
  59082. });
  59083. });
  59084. }, function (progress) {
  59085. if (_this._progressCallback) {
  59086. _this._progressCallback(progress);
  59087. }
  59088. }, function (scene, message) {
  59089. _this._currentScene = scene;
  59090. if (_this._errorCallback) {
  59091. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  59092. }
  59093. });
  59094. }
  59095. else {
  59096. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  59097. }
  59098. };
  59099. FilesInput.FilesToLoad = {};
  59100. return FilesInput;
  59101. }());
  59102. BABYLON.FilesInput = FilesInput;
  59103. })(BABYLON || (BABYLON = {}));
  59104. //# sourceMappingURL=babylon.filesInput.js.map
  59105. var BABYLON;
  59106. (function (BABYLON) {
  59107. /**
  59108. * This class implement a typical dictionary using a string as key and the generic type T as value.
  59109. * The underlying implementation relies on an associative array to ensure the best performances.
  59110. * The value can be anything including 'null' but except 'undefined'
  59111. */
  59112. var StringDictionary = /** @class */ (function () {
  59113. function StringDictionary() {
  59114. this._count = 0;
  59115. this._data = {};
  59116. }
  59117. /**
  59118. * This will clear this dictionary and copy the content from the 'source' one.
  59119. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  59120. * @param source the dictionary to take the content from and copy to this dictionary
  59121. */
  59122. StringDictionary.prototype.copyFrom = function (source) {
  59123. var _this = this;
  59124. this.clear();
  59125. source.forEach(function (t, v) { return _this.add(t, v); });
  59126. };
  59127. /**
  59128. * Get a value based from its key
  59129. * @param key the given key to get the matching value from
  59130. * @return the value if found, otherwise undefined is returned
  59131. */
  59132. StringDictionary.prototype.get = function (key) {
  59133. var val = this._data[key];
  59134. if (val !== undefined) {
  59135. return val;
  59136. }
  59137. return undefined;
  59138. };
  59139. /**
  59140. * Get a value from its key or add it if it doesn't exist.
  59141. * This method will ensure you that a given key/data will be present in the dictionary.
  59142. * @param key the given key to get the matching value from
  59143. * @param factory the factory that will create the value if the key is not present in the dictionary.
  59144. * The factory will only be invoked if there's no data for the given key.
  59145. * @return the value corresponding to the key.
  59146. */
  59147. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  59148. var val = this.get(key);
  59149. if (val !== undefined) {
  59150. return val;
  59151. }
  59152. val = factory(key);
  59153. if (val) {
  59154. this.add(key, val);
  59155. }
  59156. return val;
  59157. };
  59158. /**
  59159. * Get a value from its key if present in the dictionary otherwise add it
  59160. * @param key the key to get the value from
  59161. * @param val if there's no such key/value pair in the dictionary add it with this value
  59162. * @return the value corresponding to the key
  59163. */
  59164. StringDictionary.prototype.getOrAdd = function (key, val) {
  59165. var curVal = this.get(key);
  59166. if (curVal !== undefined) {
  59167. return curVal;
  59168. }
  59169. this.add(key, val);
  59170. return val;
  59171. };
  59172. /**
  59173. * Check if there's a given key in the dictionary
  59174. * @param key the key to check for
  59175. * @return true if the key is present, false otherwise
  59176. */
  59177. StringDictionary.prototype.contains = function (key) {
  59178. return this._data[key] !== undefined;
  59179. };
  59180. /**
  59181. * Add a new key and its corresponding value
  59182. * @param key the key to add
  59183. * @param value the value corresponding to the key
  59184. * @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
  59185. */
  59186. StringDictionary.prototype.add = function (key, value) {
  59187. if (this._data[key] !== undefined) {
  59188. return false;
  59189. }
  59190. this._data[key] = value;
  59191. ++this._count;
  59192. return true;
  59193. };
  59194. StringDictionary.prototype.set = function (key, value) {
  59195. if (this._data[key] === undefined) {
  59196. return false;
  59197. }
  59198. this._data[key] = value;
  59199. return true;
  59200. };
  59201. /**
  59202. * Get the element of the given key and remove it from the dictionary
  59203. * @param key
  59204. */
  59205. StringDictionary.prototype.getAndRemove = function (key) {
  59206. var val = this.get(key);
  59207. if (val !== undefined) {
  59208. delete this._data[key];
  59209. --this._count;
  59210. return val;
  59211. }
  59212. return null;
  59213. };
  59214. /**
  59215. * Remove a key/value from the dictionary.
  59216. * @param key the key to remove
  59217. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  59218. */
  59219. StringDictionary.prototype.remove = function (key) {
  59220. if (this.contains(key)) {
  59221. delete this._data[key];
  59222. --this._count;
  59223. return true;
  59224. }
  59225. return false;
  59226. };
  59227. /**
  59228. * Clear the whole content of the dictionary
  59229. */
  59230. StringDictionary.prototype.clear = function () {
  59231. this._data = {};
  59232. this._count = 0;
  59233. };
  59234. Object.defineProperty(StringDictionary.prototype, "count", {
  59235. get: function () {
  59236. return this._count;
  59237. },
  59238. enumerable: true,
  59239. configurable: true
  59240. });
  59241. /**
  59242. * Execute a callback on each key/val of the dictionary.
  59243. * Note that you can remove any element in this dictionary in the callback implementation
  59244. * @param callback the callback to execute on a given key/value pair
  59245. */
  59246. StringDictionary.prototype.forEach = function (callback) {
  59247. for (var cur in this._data) {
  59248. var val = this._data[cur];
  59249. callback(cur, val);
  59250. }
  59251. };
  59252. /**
  59253. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  59254. * If the callback returns null or undefined the method will iterate to the next key/value pair
  59255. * Note that you can remove any element in this dictionary in the callback implementation
  59256. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  59257. */
  59258. StringDictionary.prototype.first = function (callback) {
  59259. for (var cur in this._data) {
  59260. var val = this._data[cur];
  59261. var res = callback(cur, val);
  59262. if (res) {
  59263. return res;
  59264. }
  59265. }
  59266. return null;
  59267. };
  59268. return StringDictionary;
  59269. }());
  59270. BABYLON.StringDictionary = StringDictionary;
  59271. })(BABYLON || (BABYLON = {}));
  59272. //# sourceMappingURL=babylon.stringDictionary.js.map
  59273. var BABYLON;
  59274. (function (BABYLON) {
  59275. var Tags = /** @class */ (function () {
  59276. function Tags() {
  59277. }
  59278. Tags.EnableFor = function (obj) {
  59279. obj._tags = obj._tags || {};
  59280. obj.hasTags = function () {
  59281. return Tags.HasTags(obj);
  59282. };
  59283. obj.addTags = function (tagsString) {
  59284. return Tags.AddTagsTo(obj, tagsString);
  59285. };
  59286. obj.removeTags = function (tagsString) {
  59287. return Tags.RemoveTagsFrom(obj, tagsString);
  59288. };
  59289. obj.matchesTagsQuery = function (tagsQuery) {
  59290. return Tags.MatchesQuery(obj, tagsQuery);
  59291. };
  59292. };
  59293. Tags.DisableFor = function (obj) {
  59294. delete obj._tags;
  59295. delete obj.hasTags;
  59296. delete obj.addTags;
  59297. delete obj.removeTags;
  59298. delete obj.matchesTagsQuery;
  59299. };
  59300. Tags.HasTags = function (obj) {
  59301. if (!obj._tags) {
  59302. return false;
  59303. }
  59304. return !BABYLON.Tools.IsEmpty(obj._tags);
  59305. };
  59306. Tags.GetTags = function (obj, asString) {
  59307. if (asString === void 0) { asString = true; }
  59308. if (!obj._tags) {
  59309. return null;
  59310. }
  59311. if (asString) {
  59312. var tagsArray = [];
  59313. for (var tag in obj._tags) {
  59314. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  59315. tagsArray.push(tag);
  59316. }
  59317. }
  59318. return tagsArray.join(" ");
  59319. }
  59320. else {
  59321. return obj._tags;
  59322. }
  59323. };
  59324. // the tags 'true' and 'false' are reserved and cannot be used as tags
  59325. // a tag cannot start with '||', '&&', and '!'
  59326. // it cannot contain whitespaces
  59327. Tags.AddTagsTo = function (obj, tagsString) {
  59328. if (!tagsString) {
  59329. return;
  59330. }
  59331. if (typeof tagsString !== "string") {
  59332. return;
  59333. }
  59334. var tags = tagsString.split(" ");
  59335. tags.forEach(function (tag, index, array) {
  59336. Tags._AddTagTo(obj, tag);
  59337. });
  59338. };
  59339. Tags._AddTagTo = function (obj, tag) {
  59340. tag = tag.trim();
  59341. if (tag === "" || tag === "true" || tag === "false") {
  59342. return;
  59343. }
  59344. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  59345. return;
  59346. }
  59347. Tags.EnableFor(obj);
  59348. obj._tags[tag] = true;
  59349. };
  59350. Tags.RemoveTagsFrom = function (obj, tagsString) {
  59351. if (!Tags.HasTags(obj)) {
  59352. return;
  59353. }
  59354. var tags = tagsString.split(" ");
  59355. for (var t in tags) {
  59356. Tags._RemoveTagFrom(obj, tags[t]);
  59357. }
  59358. };
  59359. Tags._RemoveTagFrom = function (obj, tag) {
  59360. delete obj._tags[tag];
  59361. };
  59362. Tags.MatchesQuery = function (obj, tagsQuery) {
  59363. if (tagsQuery === undefined) {
  59364. return true;
  59365. }
  59366. if (tagsQuery === "") {
  59367. return Tags.HasTags(obj);
  59368. }
  59369. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  59370. };
  59371. return Tags;
  59372. }());
  59373. BABYLON.Tags = Tags;
  59374. })(BABYLON || (BABYLON = {}));
  59375. //# sourceMappingURL=babylon.tags.js.map
  59376. var BABYLON;
  59377. (function (BABYLON) {
  59378. var AndOrNotEvaluator = /** @class */ (function () {
  59379. function AndOrNotEvaluator() {
  59380. }
  59381. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  59382. if (!query.match(/\([^\(\)]*\)/g)) {
  59383. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  59384. }
  59385. else {
  59386. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  59387. // remove parenthesis
  59388. r = r.slice(1, r.length - 1);
  59389. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  59390. });
  59391. }
  59392. if (query === "true") {
  59393. return true;
  59394. }
  59395. if (query === "false") {
  59396. return false;
  59397. }
  59398. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  59399. };
  59400. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  59401. evaluateCallback = evaluateCallback || (function (r) {
  59402. return r === "true" ? true : false;
  59403. });
  59404. var result;
  59405. var or = parenthesisContent.split("||");
  59406. for (var i in or) {
  59407. if (or.hasOwnProperty(i)) {
  59408. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  59409. var and = ori.split("&&");
  59410. if (and.length > 1) {
  59411. for (var j = 0; j < and.length; ++j) {
  59412. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  59413. if (andj !== "true" && andj !== "false") {
  59414. if (andj[0] === "!") {
  59415. result = !evaluateCallback(andj.substring(1));
  59416. }
  59417. else {
  59418. result = evaluateCallback(andj);
  59419. }
  59420. }
  59421. else {
  59422. result = andj === "true" ? true : false;
  59423. }
  59424. if (!result) {
  59425. ori = "false";
  59426. break;
  59427. }
  59428. }
  59429. }
  59430. if (result || ori === "true") {
  59431. result = true;
  59432. break;
  59433. }
  59434. // result equals false (or undefined)
  59435. if (ori !== "true" && ori !== "false") {
  59436. if (ori[0] === "!") {
  59437. result = !evaluateCallback(ori.substring(1));
  59438. }
  59439. else {
  59440. result = evaluateCallback(ori);
  59441. }
  59442. }
  59443. else {
  59444. result = ori === "true" ? true : false;
  59445. }
  59446. }
  59447. }
  59448. // the whole parenthesis scope is replaced by 'true' or 'false'
  59449. return result ? "true" : "false";
  59450. };
  59451. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  59452. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  59453. // remove whitespaces
  59454. r = r.replace(/[\s]/g, function () { return ""; });
  59455. return r.length % 2 ? "!" : "";
  59456. });
  59457. booleanString = booleanString.trim();
  59458. if (booleanString === "!true") {
  59459. booleanString = "false";
  59460. }
  59461. else if (booleanString === "!false") {
  59462. booleanString = "true";
  59463. }
  59464. return booleanString;
  59465. };
  59466. return AndOrNotEvaluator;
  59467. }());
  59468. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  59469. })(BABYLON || (BABYLON = {}));
  59470. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  59471. var BABYLON;
  59472. (function (BABYLON) {
  59473. var Database = /** @class */ (function () {
  59474. function Database(urlToScene, callbackManifestChecked) {
  59475. // Handling various flavors of prefixed version of IndexedDB
  59476. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  59477. this.callbackManifestChecked = callbackManifestChecked;
  59478. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  59479. this.db = null;
  59480. this._enableSceneOffline = false;
  59481. this._enableTexturesOffline = false;
  59482. this.manifestVersionFound = 0;
  59483. this.mustUpdateRessources = false;
  59484. this.hasReachedQuota = false;
  59485. if (!Database.IDBStorageEnabled) {
  59486. this.callbackManifestChecked(true);
  59487. }
  59488. else {
  59489. this.checkManifestFile();
  59490. }
  59491. }
  59492. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  59493. get: function () {
  59494. return this._enableSceneOffline;
  59495. },
  59496. enumerable: true,
  59497. configurable: true
  59498. });
  59499. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  59500. get: function () {
  59501. return this._enableTexturesOffline;
  59502. },
  59503. enumerable: true,
  59504. configurable: true
  59505. });
  59506. Database.prototype.checkManifestFile = function () {
  59507. var _this = this;
  59508. var noManifestFile = function () {
  59509. _this._enableSceneOffline = false;
  59510. _this._enableTexturesOffline = false;
  59511. _this.callbackManifestChecked(false);
  59512. };
  59513. var timeStampUsed = false;
  59514. var manifestURL = this.currentSceneUrl + ".manifest";
  59515. var xhr = new XMLHttpRequest();
  59516. if (navigator.onLine) {
  59517. // Adding a timestamp to by-pass browsers' cache
  59518. timeStampUsed = true;
  59519. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  59520. }
  59521. xhr.open("GET", manifestURL, true);
  59522. xhr.addEventListener("load", function () {
  59523. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  59524. try {
  59525. var manifestFile = JSON.parse(xhr.response);
  59526. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  59527. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  59528. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  59529. _this.manifestVersionFound = manifestFile.version;
  59530. }
  59531. if (_this.callbackManifestChecked) {
  59532. _this.callbackManifestChecked(true);
  59533. }
  59534. }
  59535. catch (ex) {
  59536. noManifestFile();
  59537. }
  59538. }
  59539. else {
  59540. noManifestFile();
  59541. }
  59542. }, false);
  59543. xhr.addEventListener("error", function (event) {
  59544. if (timeStampUsed) {
  59545. timeStampUsed = false;
  59546. // Let's retry without the timeStamp
  59547. // It could fail when coupled with HTML5 Offline API
  59548. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  59549. xhr.open("GET", retryManifestURL, true);
  59550. xhr.send();
  59551. }
  59552. else {
  59553. noManifestFile();
  59554. }
  59555. }, false);
  59556. try {
  59557. xhr.send();
  59558. }
  59559. catch (ex) {
  59560. BABYLON.Tools.Error("Error on XHR send request.");
  59561. this.callbackManifestChecked(false);
  59562. }
  59563. };
  59564. Database.prototype.openAsync = function (successCallback, errorCallback) {
  59565. var _this = this;
  59566. var handleError = function () {
  59567. _this.isSupported = false;
  59568. if (errorCallback)
  59569. errorCallback();
  59570. };
  59571. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  59572. // Your browser doesn't support IndexedDB
  59573. this.isSupported = false;
  59574. if (errorCallback)
  59575. errorCallback();
  59576. }
  59577. else {
  59578. // If the DB hasn't been opened or created yet
  59579. if (!this.db) {
  59580. this.hasReachedQuota = false;
  59581. this.isSupported = true;
  59582. var request = this.idbFactory.open("babylonjs", 1);
  59583. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  59584. request.onerror = function (event) {
  59585. handleError();
  59586. };
  59587. // executes when a version change transaction cannot complete due to other active transactions
  59588. request.onblocked = function (event) {
  59589. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  59590. handleError();
  59591. };
  59592. // DB has been opened successfully
  59593. request.onsuccess = function (event) {
  59594. _this.db = request.result;
  59595. successCallback();
  59596. };
  59597. // Initialization of the DB. Creating Scenes & Textures stores
  59598. request.onupgradeneeded = function (event) {
  59599. _this.db = (event.target).result;
  59600. if (_this.db) {
  59601. try {
  59602. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  59603. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  59604. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  59605. }
  59606. catch (ex) {
  59607. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  59608. handleError();
  59609. }
  59610. }
  59611. };
  59612. }
  59613. else {
  59614. if (successCallback)
  59615. successCallback();
  59616. }
  59617. }
  59618. };
  59619. Database.prototype.loadImageFromDB = function (url, image) {
  59620. var _this = this;
  59621. var completeURL = Database.ReturnFullUrlLocation(url);
  59622. var saveAndLoadImage = function () {
  59623. if (!_this.hasReachedQuota && _this.db !== null) {
  59624. // the texture is not yet in the DB, let's try to save it
  59625. _this._saveImageIntoDBAsync(completeURL, image);
  59626. }
  59627. else {
  59628. image.src = url;
  59629. }
  59630. };
  59631. if (!this.mustUpdateRessources) {
  59632. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  59633. }
  59634. else {
  59635. saveAndLoadImage();
  59636. }
  59637. };
  59638. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  59639. if (this.isSupported && this.db !== null) {
  59640. var texture;
  59641. var transaction = this.db.transaction(["textures"]);
  59642. transaction.onabort = function (event) {
  59643. image.src = url;
  59644. };
  59645. transaction.oncomplete = function (event) {
  59646. var blobTextureURL;
  59647. if (texture) {
  59648. var URL = window.URL || window.webkitURL;
  59649. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  59650. image.onerror = function () {
  59651. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  59652. image.src = url;
  59653. };
  59654. image.src = blobTextureURL;
  59655. }
  59656. else {
  59657. notInDBCallback();
  59658. }
  59659. };
  59660. var getRequest = transaction.objectStore("textures").get(url);
  59661. getRequest.onsuccess = function (event) {
  59662. texture = (event.target).result;
  59663. };
  59664. getRequest.onerror = function (event) {
  59665. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  59666. image.src = url;
  59667. };
  59668. }
  59669. else {
  59670. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59671. image.src = url;
  59672. }
  59673. };
  59674. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  59675. var _this = this;
  59676. if (this.isSupported) {
  59677. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  59678. var generateBlobUrl = function () {
  59679. var blobTextureURL;
  59680. if (blob) {
  59681. var URL = window.URL || window.webkitURL;
  59682. try {
  59683. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  59684. }
  59685. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  59686. catch (ex) {
  59687. blobTextureURL = URL.createObjectURL(blob);
  59688. }
  59689. }
  59690. if (blobTextureURL) {
  59691. image.src = blobTextureURL;
  59692. }
  59693. };
  59694. if (Database.IsUASupportingBlobStorage) {
  59695. var xhr = new XMLHttpRequest(), blob;
  59696. xhr.open("GET", url, true);
  59697. xhr.responseType = "blob";
  59698. xhr.addEventListener("load", function () {
  59699. if (xhr.status === 200 && _this.db) {
  59700. // Blob as response (XHR2)
  59701. blob = xhr.response;
  59702. var transaction = _this.db.transaction(["textures"], "readwrite");
  59703. // the transaction could abort because of a QuotaExceededError error
  59704. transaction.onabort = function (event) {
  59705. try {
  59706. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59707. var srcElement = (event.srcElement || event.target);
  59708. var error = srcElement.error;
  59709. if (error && error.name === "QuotaExceededError") {
  59710. _this.hasReachedQuota = true;
  59711. }
  59712. }
  59713. catch (ex) { }
  59714. generateBlobUrl();
  59715. };
  59716. transaction.oncomplete = function (event) {
  59717. generateBlobUrl();
  59718. };
  59719. var newTexture = { textureUrl: url, data: blob };
  59720. try {
  59721. // Put the blob into the dabase
  59722. var addRequest = transaction.objectStore("textures").put(newTexture);
  59723. addRequest.onsuccess = function (event) {
  59724. };
  59725. addRequest.onerror = function (event) {
  59726. generateBlobUrl();
  59727. };
  59728. }
  59729. catch (ex) {
  59730. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  59731. if (ex.code === 25) {
  59732. Database.IsUASupportingBlobStorage = false;
  59733. }
  59734. image.src = url;
  59735. }
  59736. }
  59737. else {
  59738. image.src = url;
  59739. }
  59740. }, false);
  59741. xhr.addEventListener("error", function (event) {
  59742. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  59743. image.src = url;
  59744. }, false);
  59745. xhr.send();
  59746. }
  59747. else {
  59748. image.src = url;
  59749. }
  59750. }
  59751. else {
  59752. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59753. image.src = url;
  59754. }
  59755. };
  59756. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  59757. var _this = this;
  59758. var updateVersion = function () {
  59759. // the version is not yet in the DB or we need to update it
  59760. _this._saveVersionIntoDBAsync(url, versionLoaded);
  59761. };
  59762. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  59763. };
  59764. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  59765. var _this = this;
  59766. if (this.isSupported && this.db) {
  59767. var version;
  59768. try {
  59769. var transaction = this.db.transaction(["versions"]);
  59770. transaction.oncomplete = function (event) {
  59771. if (version) {
  59772. // If the version in the JSON file is > than the version in DB
  59773. if (_this.manifestVersionFound > version.data) {
  59774. _this.mustUpdateRessources = true;
  59775. updateInDBCallback();
  59776. }
  59777. else {
  59778. callback(version.data);
  59779. }
  59780. }
  59781. else {
  59782. _this.mustUpdateRessources = true;
  59783. updateInDBCallback();
  59784. }
  59785. };
  59786. transaction.onabort = function (event) {
  59787. callback(-1);
  59788. };
  59789. var getRequest = transaction.objectStore("versions").get(url);
  59790. getRequest.onsuccess = function (event) {
  59791. version = (event.target).result;
  59792. };
  59793. getRequest.onerror = function (event) {
  59794. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  59795. callback(-1);
  59796. };
  59797. }
  59798. catch (ex) {
  59799. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  59800. callback(-1);
  59801. }
  59802. }
  59803. else {
  59804. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59805. callback(-1);
  59806. }
  59807. };
  59808. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  59809. var _this = this;
  59810. if (this.isSupported && !this.hasReachedQuota && this.db) {
  59811. try {
  59812. // Open a transaction to the database
  59813. var transaction = this.db.transaction(["versions"], "readwrite");
  59814. // the transaction could abort because of a QuotaExceededError error
  59815. transaction.onabort = function (event) {
  59816. try {
  59817. var error = event.srcElement['error'];
  59818. if (error && error.name === "QuotaExceededError") {
  59819. _this.hasReachedQuota = true;
  59820. }
  59821. }
  59822. catch (ex) { }
  59823. callback(-1);
  59824. };
  59825. transaction.oncomplete = function (event) {
  59826. callback(_this.manifestVersionFound);
  59827. };
  59828. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  59829. // Put the scene into the database
  59830. var addRequest = transaction.objectStore("versions").put(newVersion);
  59831. addRequest.onsuccess = function (event) {
  59832. };
  59833. addRequest.onerror = function (event) {
  59834. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  59835. };
  59836. }
  59837. catch (ex) {
  59838. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  59839. callback(-1);
  59840. }
  59841. }
  59842. else {
  59843. callback(-1);
  59844. }
  59845. };
  59846. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  59847. var _this = this;
  59848. var completeUrl = Database.ReturnFullUrlLocation(url);
  59849. var saveAndLoadFile = function () {
  59850. // the scene is not yet in the DB, let's try to save it
  59851. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  59852. };
  59853. this._checkVersionFromDB(completeUrl, function (version) {
  59854. if (version !== -1) {
  59855. if (!_this.mustUpdateRessources) {
  59856. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  59857. }
  59858. else {
  59859. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  59860. }
  59861. }
  59862. else {
  59863. if (errorCallback) {
  59864. errorCallback();
  59865. }
  59866. }
  59867. });
  59868. };
  59869. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  59870. if (this.isSupported && this.db) {
  59871. var targetStore;
  59872. if (url.indexOf(".babylon") !== -1) {
  59873. targetStore = "scenes";
  59874. }
  59875. else {
  59876. targetStore = "textures";
  59877. }
  59878. var file;
  59879. var transaction = this.db.transaction([targetStore]);
  59880. transaction.oncomplete = function (event) {
  59881. if (file) {
  59882. callback(file.data);
  59883. }
  59884. else {
  59885. notInDBCallback();
  59886. }
  59887. };
  59888. transaction.onabort = function (event) {
  59889. notInDBCallback();
  59890. };
  59891. var getRequest = transaction.objectStore(targetStore).get(url);
  59892. getRequest.onsuccess = function (event) {
  59893. file = (event.target).result;
  59894. };
  59895. getRequest.onerror = function (event) {
  59896. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  59897. notInDBCallback();
  59898. };
  59899. }
  59900. else {
  59901. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59902. callback();
  59903. }
  59904. };
  59905. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  59906. var _this = this;
  59907. if (this.isSupported) {
  59908. var targetStore;
  59909. if (url.indexOf(".babylon") !== -1) {
  59910. targetStore = "scenes";
  59911. }
  59912. else {
  59913. targetStore = "textures";
  59914. }
  59915. // Create XHR
  59916. var xhr = new XMLHttpRequest();
  59917. var fileData;
  59918. xhr.open("GET", url, true);
  59919. if (useArrayBuffer) {
  59920. xhr.responseType = "arraybuffer";
  59921. }
  59922. if (progressCallback) {
  59923. xhr.onprogress = progressCallback;
  59924. }
  59925. xhr.addEventListener("load", function () {
  59926. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  59927. // Blob as response (XHR2)
  59928. //fileData = xhr.responseText;
  59929. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  59930. if (!_this.hasReachedQuota && _this.db) {
  59931. // Open a transaction to the database
  59932. var transaction = _this.db.transaction([targetStore], "readwrite");
  59933. // the transaction could abort because of a QuotaExceededError error
  59934. transaction.onabort = function (event) {
  59935. try {
  59936. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59937. var error = event.srcElement['error'];
  59938. if (error && error.name === "QuotaExceededError") {
  59939. _this.hasReachedQuota = true;
  59940. }
  59941. }
  59942. catch (ex) { }
  59943. callback(fileData);
  59944. };
  59945. transaction.oncomplete = function (event) {
  59946. callback(fileData);
  59947. };
  59948. var newFile;
  59949. if (targetStore === "scenes") {
  59950. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  59951. }
  59952. else {
  59953. newFile = { textureUrl: url, data: fileData };
  59954. }
  59955. try {
  59956. // Put the scene into the database
  59957. var addRequest = transaction.objectStore(targetStore).put(newFile);
  59958. addRequest.onsuccess = function (event) {
  59959. };
  59960. addRequest.onerror = function (event) {
  59961. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  59962. };
  59963. }
  59964. catch (ex) {
  59965. callback(fileData);
  59966. }
  59967. }
  59968. else {
  59969. callback(fileData);
  59970. }
  59971. }
  59972. else {
  59973. callback();
  59974. }
  59975. }, false);
  59976. xhr.addEventListener("error", function (event) {
  59977. BABYLON.Tools.Error("error on XHR request.");
  59978. callback();
  59979. }, false);
  59980. xhr.send();
  59981. }
  59982. else {
  59983. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59984. callback();
  59985. }
  59986. };
  59987. Database.IsUASupportingBlobStorage = true;
  59988. Database.IDBStorageEnabled = true;
  59989. Database.parseURL = function (url) {
  59990. var a = document.createElement('a');
  59991. a.href = url;
  59992. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  59993. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  59994. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  59995. return absLocation;
  59996. };
  59997. Database.ReturnFullUrlLocation = function (url) {
  59998. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  59999. return (Database.parseURL(window.location.href) + url);
  60000. }
  60001. else {
  60002. return url;
  60003. }
  60004. };
  60005. return Database;
  60006. }());
  60007. BABYLON.Database = Database;
  60008. })(BABYLON || (BABYLON = {}));
  60009. //# sourceMappingURL=babylon.database.js.map
  60010. var BABYLON;
  60011. (function (BABYLON) {
  60012. var FresnelParameters = /** @class */ (function () {
  60013. function FresnelParameters() {
  60014. this._isEnabled = true;
  60015. this.leftColor = BABYLON.Color3.White();
  60016. this.rightColor = BABYLON.Color3.Black();
  60017. this.bias = 0;
  60018. this.power = 1;
  60019. }
  60020. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  60021. get: function () {
  60022. return this._isEnabled;
  60023. },
  60024. set: function (value) {
  60025. if (this._isEnabled === value) {
  60026. return;
  60027. }
  60028. this._isEnabled = value;
  60029. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  60030. },
  60031. enumerable: true,
  60032. configurable: true
  60033. });
  60034. FresnelParameters.prototype.clone = function () {
  60035. var newFresnelParameters = new FresnelParameters();
  60036. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  60037. return newFresnelParameters;
  60038. };
  60039. FresnelParameters.prototype.serialize = function () {
  60040. var serializationObject = {};
  60041. serializationObject.isEnabled = this.isEnabled;
  60042. serializationObject.leftColor = this.leftColor;
  60043. serializationObject.rightColor = this.rightColor;
  60044. serializationObject.bias = this.bias;
  60045. serializationObject.power = this.power;
  60046. return serializationObject;
  60047. };
  60048. FresnelParameters.Parse = function (parsedFresnelParameters) {
  60049. var fresnelParameters = new FresnelParameters();
  60050. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  60051. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  60052. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  60053. fresnelParameters.bias = parsedFresnelParameters.bias;
  60054. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  60055. return fresnelParameters;
  60056. };
  60057. return FresnelParameters;
  60058. }());
  60059. BABYLON.FresnelParameters = FresnelParameters;
  60060. })(BABYLON || (BABYLON = {}));
  60061. //# sourceMappingURL=babylon.fresnelParameters.js.map
  60062. var BABYLON;
  60063. (function (BABYLON) {
  60064. var MultiMaterial = /** @class */ (function (_super) {
  60065. __extends(MultiMaterial, _super);
  60066. function MultiMaterial(name, scene) {
  60067. var _this = _super.call(this, name, scene, true) || this;
  60068. scene.multiMaterials.push(_this);
  60069. _this.subMaterials = new Array();
  60070. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  60071. return _this;
  60072. }
  60073. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  60074. get: function () {
  60075. return this._subMaterials;
  60076. },
  60077. set: function (value) {
  60078. this._subMaterials = value;
  60079. this._hookArray(value);
  60080. },
  60081. enumerable: true,
  60082. configurable: true
  60083. });
  60084. MultiMaterial.prototype._hookArray = function (array) {
  60085. var _this = this;
  60086. var oldPush = array.push;
  60087. array.push = function () {
  60088. var items = [];
  60089. for (var _i = 0; _i < arguments.length; _i++) {
  60090. items[_i] = arguments[_i];
  60091. }
  60092. var result = oldPush.apply(array, items);
  60093. _this._markAllSubMeshesAsTexturesDirty();
  60094. return result;
  60095. };
  60096. var oldSplice = array.splice;
  60097. array.splice = function (index, deleteCount) {
  60098. var deleted = oldSplice.apply(array, [index, deleteCount]);
  60099. _this._markAllSubMeshesAsTexturesDirty();
  60100. return deleted;
  60101. };
  60102. };
  60103. // Properties
  60104. MultiMaterial.prototype.getSubMaterial = function (index) {
  60105. if (index < 0 || index >= this.subMaterials.length) {
  60106. return this.getScene().defaultMaterial;
  60107. }
  60108. return this.subMaterials[index];
  60109. };
  60110. MultiMaterial.prototype.getActiveTextures = function () {
  60111. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  60112. if (subMaterial) {
  60113. return subMaterial.getActiveTextures();
  60114. }
  60115. else {
  60116. return [];
  60117. }
  60118. }));
  60119. var _a;
  60120. };
  60121. // Methods
  60122. MultiMaterial.prototype.getClassName = function () {
  60123. return "MultiMaterial";
  60124. };
  60125. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  60126. for (var index = 0; index < this.subMaterials.length; index++) {
  60127. var subMaterial = this.subMaterials[index];
  60128. if (subMaterial) {
  60129. if (subMaterial.storeEffectOnSubMeshes) {
  60130. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  60131. return false;
  60132. }
  60133. continue;
  60134. }
  60135. if (!subMaterial.isReady(mesh)) {
  60136. return false;
  60137. }
  60138. }
  60139. }
  60140. return true;
  60141. };
  60142. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  60143. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  60144. for (var index = 0; index < this.subMaterials.length; index++) {
  60145. var subMaterial = null;
  60146. var current = this.subMaterials[index];
  60147. if (cloneChildren && current) {
  60148. subMaterial = current.clone(name + "-" + current.name);
  60149. }
  60150. else {
  60151. subMaterial = this.subMaterials[index];
  60152. }
  60153. newMultiMaterial.subMaterials.push(subMaterial);
  60154. }
  60155. return newMultiMaterial;
  60156. };
  60157. MultiMaterial.prototype.serialize = function () {
  60158. var serializationObject = {};
  60159. serializationObject.name = this.name;
  60160. serializationObject.id = this.id;
  60161. if (BABYLON.Tags) {
  60162. serializationObject.tags = BABYLON.Tags.GetTags(this);
  60163. }
  60164. serializationObject.materials = [];
  60165. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  60166. var subMat = this.subMaterials[matIndex];
  60167. if (subMat) {
  60168. serializationObject.materials.push(subMat.id);
  60169. }
  60170. else {
  60171. serializationObject.materials.push(null);
  60172. }
  60173. }
  60174. return serializationObject;
  60175. };
  60176. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60177. var scene = this.getScene();
  60178. if (!scene) {
  60179. return;
  60180. }
  60181. var index = scene.multiMaterials.indexOf(this);
  60182. if (index >= 0) {
  60183. scene.multiMaterials.splice(index, 1);
  60184. }
  60185. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60186. };
  60187. return MultiMaterial;
  60188. }(BABYLON.Material));
  60189. BABYLON.MultiMaterial = MultiMaterial;
  60190. })(BABYLON || (BABYLON = {}));
  60191. //# sourceMappingURL=babylon.multiMaterial.js.map
  60192. var BABYLON;
  60193. (function (BABYLON) {
  60194. var FreeCameraTouchInput = /** @class */ (function () {
  60195. function FreeCameraTouchInput() {
  60196. this._offsetX = null;
  60197. this._offsetY = null;
  60198. this._pointerPressed = new Array();
  60199. this.touchAngularSensibility = 200000.0;
  60200. this.touchMoveSensibility = 250.0;
  60201. }
  60202. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  60203. var _this = this;
  60204. var previousPosition = null;
  60205. if (this._pointerInput === undefined) {
  60206. this._onLostFocus = function (evt) {
  60207. _this._offsetX = null;
  60208. _this._offsetY = null;
  60209. };
  60210. this._pointerInput = function (p, s) {
  60211. var evt = p.event;
  60212. if (evt.pointerType === "mouse") {
  60213. return;
  60214. }
  60215. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  60216. if (!noPreventDefault) {
  60217. evt.preventDefault();
  60218. }
  60219. _this._pointerPressed.push(evt.pointerId);
  60220. if (_this._pointerPressed.length !== 1) {
  60221. return;
  60222. }
  60223. previousPosition = {
  60224. x: evt.clientX,
  60225. y: evt.clientY
  60226. };
  60227. }
  60228. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  60229. if (!noPreventDefault) {
  60230. evt.preventDefault();
  60231. }
  60232. var index = _this._pointerPressed.indexOf(evt.pointerId);
  60233. if (index === -1) {
  60234. return;
  60235. }
  60236. _this._pointerPressed.splice(index, 1);
  60237. if (index != 0) {
  60238. return;
  60239. }
  60240. previousPosition = null;
  60241. _this._offsetX = null;
  60242. _this._offsetY = null;
  60243. }
  60244. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  60245. if (!noPreventDefault) {
  60246. evt.preventDefault();
  60247. }
  60248. if (!previousPosition) {
  60249. return;
  60250. }
  60251. var index = _this._pointerPressed.indexOf(evt.pointerId);
  60252. if (index != 0) {
  60253. return;
  60254. }
  60255. _this._offsetX = evt.clientX - previousPosition.x;
  60256. _this._offsetY = -(evt.clientY - previousPosition.y);
  60257. }
  60258. };
  60259. }
  60260. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  60261. if (this._onLostFocus) {
  60262. element.addEventListener("blur", this._onLostFocus);
  60263. }
  60264. };
  60265. FreeCameraTouchInput.prototype.detachControl = function (element) {
  60266. if (this._pointerInput && element) {
  60267. if (this._observer) {
  60268. this.camera.getScene().onPointerObservable.remove(this._observer);
  60269. this._observer = null;
  60270. }
  60271. if (this._onLostFocus) {
  60272. element.removeEventListener("blur", this._onLostFocus);
  60273. this._onLostFocus = null;
  60274. }
  60275. this._pointerPressed = [];
  60276. this._offsetX = null;
  60277. this._offsetY = null;
  60278. }
  60279. };
  60280. FreeCameraTouchInput.prototype.checkInputs = function () {
  60281. if (this._offsetX && this._offsetY) {
  60282. var camera = this.camera;
  60283. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  60284. if (this._pointerPressed.length > 1) {
  60285. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  60286. }
  60287. else {
  60288. var speed = camera._computeLocalCameraSpeed();
  60289. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  60290. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  60291. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  60292. }
  60293. }
  60294. };
  60295. FreeCameraTouchInput.prototype.getClassName = function () {
  60296. return "FreeCameraTouchInput";
  60297. };
  60298. FreeCameraTouchInput.prototype.getSimpleName = function () {
  60299. return "touch";
  60300. };
  60301. __decorate([
  60302. BABYLON.serialize()
  60303. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  60304. __decorate([
  60305. BABYLON.serialize()
  60306. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  60307. return FreeCameraTouchInput;
  60308. }());
  60309. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  60310. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  60311. })(BABYLON || (BABYLON = {}));
  60312. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  60313. var BABYLON;
  60314. (function (BABYLON) {
  60315. // We're mainly based on the logic defined into the FreeCamera code
  60316. var TouchCamera = /** @class */ (function (_super) {
  60317. __extends(TouchCamera, _super);
  60318. //-- end properties for backward compatibility for inputs
  60319. function TouchCamera(name, position, scene) {
  60320. var _this = _super.call(this, name, position, scene) || this;
  60321. _this.inputs.addTouch();
  60322. _this._setupInputs();
  60323. return _this;
  60324. }
  60325. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  60326. //-- Begin properties for backward compatibility for inputs
  60327. get: function () {
  60328. var touch = this.inputs.attached["touch"];
  60329. if (touch)
  60330. return touch.touchAngularSensibility;
  60331. return 0;
  60332. },
  60333. set: function (value) {
  60334. var touch = this.inputs.attached["touch"];
  60335. if (touch)
  60336. touch.touchAngularSensibility = value;
  60337. },
  60338. enumerable: true,
  60339. configurable: true
  60340. });
  60341. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  60342. get: function () {
  60343. var touch = this.inputs.attached["touch"];
  60344. if (touch)
  60345. return touch.touchMoveSensibility;
  60346. return 0;
  60347. },
  60348. set: function (value) {
  60349. var touch = this.inputs.attached["touch"];
  60350. if (touch)
  60351. touch.touchMoveSensibility = value;
  60352. },
  60353. enumerable: true,
  60354. configurable: true
  60355. });
  60356. TouchCamera.prototype.getClassName = function () {
  60357. return "TouchCamera";
  60358. };
  60359. TouchCamera.prototype._setupInputs = function () {
  60360. var mouse = this.inputs.attached["mouse"];
  60361. if (mouse) {
  60362. mouse.touchEnabled = false;
  60363. }
  60364. };
  60365. return TouchCamera;
  60366. }(BABYLON.FreeCamera));
  60367. BABYLON.TouchCamera = TouchCamera;
  60368. })(BABYLON || (BABYLON = {}));
  60369. //# sourceMappingURL=babylon.touchCamera.js.map
  60370. var BABYLON;
  60371. (function (BABYLON) {
  60372. var ProceduralTexture = /** @class */ (function (_super) {
  60373. __extends(ProceduralTexture, _super);
  60374. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  60375. if (fallbackTexture === void 0) { fallbackTexture = null; }
  60376. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60377. if (isCube === void 0) { isCube = false; }
  60378. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  60379. _this.isCube = isCube;
  60380. _this.isEnabled = true;
  60381. _this._currentRefreshId = -1;
  60382. _this._refreshRate = 1;
  60383. _this._vertexBuffers = {};
  60384. _this._uniforms = new Array();
  60385. _this._samplers = new Array();
  60386. _this._textures = {};
  60387. _this._floats = {};
  60388. _this._floatsArrays = {};
  60389. _this._colors3 = {};
  60390. _this._colors4 = {};
  60391. _this._vectors2 = {};
  60392. _this._vectors3 = {};
  60393. _this._matrices = {};
  60394. _this._fallbackTextureUsed = false;
  60395. scene._proceduralTextures.push(_this);
  60396. _this._engine = scene.getEngine();
  60397. _this.name = name;
  60398. _this.isRenderTarget = true;
  60399. _this._size = size;
  60400. _this._generateMipMaps = generateMipMaps;
  60401. _this.setFragment(fragment);
  60402. _this._fallbackTexture = fallbackTexture;
  60403. if (isCube) {
  60404. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  60405. _this.setFloat("face", 0);
  60406. }
  60407. else {
  60408. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  60409. }
  60410. // VBO
  60411. var vertices = [];
  60412. vertices.push(1, 1);
  60413. vertices.push(-1, 1);
  60414. vertices.push(-1, -1);
  60415. vertices.push(1, -1);
  60416. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  60417. _this._createIndexBuffer();
  60418. return _this;
  60419. }
  60420. ProceduralTexture.prototype._createIndexBuffer = function () {
  60421. var engine = this._engine;
  60422. // Indices
  60423. var indices = [];
  60424. indices.push(0);
  60425. indices.push(1);
  60426. indices.push(2);
  60427. indices.push(0);
  60428. indices.push(2);
  60429. indices.push(3);
  60430. this._indexBuffer = engine.createIndexBuffer(indices);
  60431. };
  60432. ProceduralTexture.prototype._rebuild = function () {
  60433. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60434. if (vb) {
  60435. vb._rebuild();
  60436. }
  60437. this._createIndexBuffer();
  60438. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  60439. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  60440. }
  60441. };
  60442. ProceduralTexture.prototype.reset = function () {
  60443. if (this._effect === undefined) {
  60444. return;
  60445. }
  60446. var engine = this._engine;
  60447. engine._releaseEffect(this._effect);
  60448. };
  60449. ProceduralTexture.prototype.isReady = function () {
  60450. var _this = this;
  60451. var engine = this._engine;
  60452. var shaders;
  60453. if (!this._fragment) {
  60454. return false;
  60455. }
  60456. if (this._fallbackTextureUsed) {
  60457. return true;
  60458. }
  60459. if (this._fragment.fragmentElement !== undefined) {
  60460. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  60461. }
  60462. else {
  60463. shaders = { vertex: "procedural", fragment: this._fragment };
  60464. }
  60465. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  60466. _this.releaseInternalTexture();
  60467. if (_this._fallbackTexture) {
  60468. _this._texture = _this._fallbackTexture._texture;
  60469. if (_this._texture) {
  60470. _this._texture.incrementReferences();
  60471. }
  60472. }
  60473. _this._fallbackTextureUsed = true;
  60474. });
  60475. return this._effect.isReady();
  60476. };
  60477. ProceduralTexture.prototype.resetRefreshCounter = function () {
  60478. this._currentRefreshId = -1;
  60479. };
  60480. ProceduralTexture.prototype.setFragment = function (fragment) {
  60481. this._fragment = fragment;
  60482. };
  60483. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  60484. get: function () {
  60485. return this._refreshRate;
  60486. },
  60487. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  60488. set: function (value) {
  60489. this._refreshRate = value;
  60490. this.resetRefreshCounter();
  60491. },
  60492. enumerable: true,
  60493. configurable: true
  60494. });
  60495. ProceduralTexture.prototype._shouldRender = function () {
  60496. if (!this.isEnabled || !this.isReady() || !this._texture) {
  60497. return false;
  60498. }
  60499. if (this._fallbackTextureUsed) {
  60500. return false;
  60501. }
  60502. if (this._currentRefreshId === -1) {
  60503. this._currentRefreshId = 1;
  60504. return true;
  60505. }
  60506. if (this.refreshRate === this._currentRefreshId) {
  60507. this._currentRefreshId = 1;
  60508. return true;
  60509. }
  60510. this._currentRefreshId++;
  60511. return false;
  60512. };
  60513. ProceduralTexture.prototype.getRenderSize = function () {
  60514. return this._size;
  60515. };
  60516. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  60517. if (this._fallbackTextureUsed) {
  60518. return;
  60519. }
  60520. this.releaseInternalTexture();
  60521. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  60522. };
  60523. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  60524. if (this._uniforms.indexOf(uniformName) === -1) {
  60525. this._uniforms.push(uniformName);
  60526. }
  60527. };
  60528. ProceduralTexture.prototype.setTexture = function (name, texture) {
  60529. if (this._samplers.indexOf(name) === -1) {
  60530. this._samplers.push(name);
  60531. }
  60532. this._textures[name] = texture;
  60533. return this;
  60534. };
  60535. ProceduralTexture.prototype.setFloat = function (name, value) {
  60536. this._checkUniform(name);
  60537. this._floats[name] = value;
  60538. return this;
  60539. };
  60540. ProceduralTexture.prototype.setFloats = function (name, value) {
  60541. this._checkUniform(name);
  60542. this._floatsArrays[name] = value;
  60543. return this;
  60544. };
  60545. ProceduralTexture.prototype.setColor3 = function (name, value) {
  60546. this._checkUniform(name);
  60547. this._colors3[name] = value;
  60548. return this;
  60549. };
  60550. ProceduralTexture.prototype.setColor4 = function (name, value) {
  60551. this._checkUniform(name);
  60552. this._colors4[name] = value;
  60553. return this;
  60554. };
  60555. ProceduralTexture.prototype.setVector2 = function (name, value) {
  60556. this._checkUniform(name);
  60557. this._vectors2[name] = value;
  60558. return this;
  60559. };
  60560. ProceduralTexture.prototype.setVector3 = function (name, value) {
  60561. this._checkUniform(name);
  60562. this._vectors3[name] = value;
  60563. return this;
  60564. };
  60565. ProceduralTexture.prototype.setMatrix = function (name, value) {
  60566. this._checkUniform(name);
  60567. this._matrices[name] = value;
  60568. return this;
  60569. };
  60570. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  60571. var scene = this.getScene();
  60572. if (!scene) {
  60573. return;
  60574. }
  60575. var engine = this._engine;
  60576. // Render
  60577. engine.enableEffect(this._effect);
  60578. engine.setState(false);
  60579. // Texture
  60580. for (var name in this._textures) {
  60581. this._effect.setTexture(name, this._textures[name]);
  60582. }
  60583. // Float
  60584. for (name in this._floats) {
  60585. this._effect.setFloat(name, this._floats[name]);
  60586. }
  60587. // Floats
  60588. for (name in this._floatsArrays) {
  60589. this._effect.setArray(name, this._floatsArrays[name]);
  60590. }
  60591. // Color3
  60592. for (name in this._colors3) {
  60593. this._effect.setColor3(name, this._colors3[name]);
  60594. }
  60595. // Color4
  60596. for (name in this._colors4) {
  60597. var color = this._colors4[name];
  60598. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60599. }
  60600. // Vector2
  60601. for (name in this._vectors2) {
  60602. this._effect.setVector2(name, this._vectors2[name]);
  60603. }
  60604. // Vector3
  60605. for (name in this._vectors3) {
  60606. this._effect.setVector3(name, this._vectors3[name]);
  60607. }
  60608. // Matrix
  60609. for (name in this._matrices) {
  60610. this._effect.setMatrix(name, this._matrices[name]);
  60611. }
  60612. if (!this._texture) {
  60613. return;
  60614. }
  60615. if (this.isCube) {
  60616. for (var face = 0; face < 6; face++) {
  60617. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  60618. // VBOs
  60619. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60620. this._effect.setFloat("face", face);
  60621. // Clear
  60622. engine.clear(scene.clearColor, true, true, true);
  60623. // Draw order
  60624. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60625. // Mipmaps
  60626. if (face === 5) {
  60627. engine.generateMipMapsForCubemap(this._texture);
  60628. }
  60629. }
  60630. }
  60631. else {
  60632. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  60633. // VBOs
  60634. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60635. // Clear
  60636. engine.clear(scene.clearColor, true, true, true);
  60637. // Draw order
  60638. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60639. }
  60640. // Unbind
  60641. engine.unBindFramebuffer(this._texture, this.isCube);
  60642. if (this.onGenerated) {
  60643. this.onGenerated();
  60644. }
  60645. };
  60646. ProceduralTexture.prototype.clone = function () {
  60647. var textureSize = this.getSize();
  60648. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  60649. // Base texture
  60650. newTexture.hasAlpha = this.hasAlpha;
  60651. newTexture.level = this.level;
  60652. // RenderTarget Texture
  60653. newTexture.coordinatesMode = this.coordinatesMode;
  60654. return newTexture;
  60655. };
  60656. ProceduralTexture.prototype.dispose = function () {
  60657. var scene = this.getScene();
  60658. if (!scene) {
  60659. return;
  60660. }
  60661. var index = scene._proceduralTextures.indexOf(this);
  60662. if (index >= 0) {
  60663. scene._proceduralTextures.splice(index, 1);
  60664. }
  60665. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60666. if (vertexBuffer) {
  60667. vertexBuffer.dispose();
  60668. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60669. }
  60670. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  60671. this._indexBuffer = null;
  60672. }
  60673. _super.prototype.dispose.call(this);
  60674. };
  60675. return ProceduralTexture;
  60676. }(BABYLON.Texture));
  60677. BABYLON.ProceduralTexture = ProceduralTexture;
  60678. })(BABYLON || (BABYLON = {}));
  60679. //# sourceMappingURL=babylon.proceduralTexture.js.map
  60680. var BABYLON;
  60681. (function (BABYLON) {
  60682. var CustomProceduralTexture = /** @class */ (function (_super) {
  60683. __extends(CustomProceduralTexture, _super);
  60684. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  60685. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  60686. _this._animate = true;
  60687. _this._time = 0;
  60688. _this._texturePath = texturePath;
  60689. //Try to load json
  60690. _this.loadJson(texturePath);
  60691. _this.refreshRate = 1;
  60692. return _this;
  60693. }
  60694. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  60695. var _this = this;
  60696. var noConfigFile = function () {
  60697. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  60698. try {
  60699. _this.setFragment(_this._texturePath);
  60700. }
  60701. catch (ex) {
  60702. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  60703. }
  60704. };
  60705. var configFileUrl = jsonUrl + "/config.json";
  60706. var xhr = new XMLHttpRequest();
  60707. xhr.open("GET", configFileUrl, true);
  60708. xhr.addEventListener("load", function () {
  60709. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  60710. try {
  60711. _this._config = JSON.parse(xhr.response);
  60712. _this.updateShaderUniforms();
  60713. _this.updateTextures();
  60714. _this.setFragment(_this._texturePath + "/custom");
  60715. _this._animate = _this._config.animate;
  60716. _this.refreshRate = _this._config.refreshrate;
  60717. }
  60718. catch (ex) {
  60719. noConfigFile();
  60720. }
  60721. }
  60722. else {
  60723. noConfigFile();
  60724. }
  60725. }, false);
  60726. xhr.addEventListener("error", function () {
  60727. noConfigFile();
  60728. }, false);
  60729. try {
  60730. xhr.send();
  60731. }
  60732. catch (ex) {
  60733. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  60734. }
  60735. };
  60736. CustomProceduralTexture.prototype.isReady = function () {
  60737. if (!_super.prototype.isReady.call(this)) {
  60738. return false;
  60739. }
  60740. for (var name in this._textures) {
  60741. var texture = this._textures[name];
  60742. if (!texture.isReady()) {
  60743. return false;
  60744. }
  60745. }
  60746. return true;
  60747. };
  60748. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  60749. var scene = this.getScene();
  60750. if (this._animate && scene) {
  60751. this._time += scene.getAnimationRatio() * 0.03;
  60752. this.updateShaderUniforms();
  60753. }
  60754. _super.prototype.render.call(this, useCameraPostProcess);
  60755. };
  60756. CustomProceduralTexture.prototype.updateTextures = function () {
  60757. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  60758. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  60759. }
  60760. };
  60761. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  60762. if (this._config) {
  60763. for (var j = 0; j < this._config.uniforms.length; j++) {
  60764. var uniform = this._config.uniforms[j];
  60765. switch (uniform.type) {
  60766. case "float":
  60767. this.setFloat(uniform.name, uniform.value);
  60768. break;
  60769. case "color3":
  60770. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  60771. break;
  60772. case "color4":
  60773. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  60774. break;
  60775. case "vector2":
  60776. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  60777. break;
  60778. case "vector3":
  60779. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  60780. break;
  60781. }
  60782. }
  60783. }
  60784. this.setFloat("time", this._time);
  60785. };
  60786. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  60787. get: function () {
  60788. return this._animate;
  60789. },
  60790. set: function (value) {
  60791. this._animate = value;
  60792. },
  60793. enumerable: true,
  60794. configurable: true
  60795. });
  60796. return CustomProceduralTexture;
  60797. }(BABYLON.ProceduralTexture));
  60798. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  60799. })(BABYLON || (BABYLON = {}));
  60800. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  60801. var BABYLON;
  60802. (function (BABYLON) {
  60803. var FreeCameraGamepadInput = /** @class */ (function () {
  60804. function FreeCameraGamepadInput() {
  60805. this.gamepadAngularSensibility = 200;
  60806. this.gamepadMoveSensibility = 40;
  60807. // private members
  60808. this._cameraTransform = BABYLON.Matrix.Identity();
  60809. this._deltaTransform = BABYLON.Vector3.Zero();
  60810. this._vector3 = BABYLON.Vector3.Zero();
  60811. this._vector2 = BABYLON.Vector2.Zero();
  60812. }
  60813. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60814. var _this = this;
  60815. var manager = this.camera.getScene().gamepadManager;
  60816. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60817. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60818. // prioritize XBOX gamepads.
  60819. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60820. _this.gamepad = gamepad;
  60821. }
  60822. }
  60823. });
  60824. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60825. if (_this.gamepad === gamepad) {
  60826. _this.gamepad = null;
  60827. }
  60828. });
  60829. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60830. };
  60831. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  60832. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60833. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60834. this.gamepad = null;
  60835. };
  60836. FreeCameraGamepadInput.prototype.checkInputs = function () {
  60837. if (this.gamepad && this.gamepad.leftStick) {
  60838. var camera = this.camera;
  60839. var LSValues = this.gamepad.leftStick;
  60840. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  60841. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60842. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  60843. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  60844. var RSValues = this.gamepad.rightStick;
  60845. if (RSValues) {
  60846. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  60847. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  60848. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  60849. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  60850. }
  60851. else {
  60852. RSValues = { x: 0, y: 0 };
  60853. }
  60854. if (!camera.rotationQuaternion) {
  60855. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  60856. }
  60857. else {
  60858. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  60859. }
  60860. var speed = camera._computeLocalCameraSpeed() * 50.0;
  60861. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  60862. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  60863. camera.cameraDirection.addInPlace(this._deltaTransform);
  60864. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  60865. camera.cameraRotation.addInPlace(this._vector2);
  60866. }
  60867. };
  60868. FreeCameraGamepadInput.prototype.getClassName = function () {
  60869. return "FreeCameraGamepadInput";
  60870. };
  60871. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  60872. return "gamepad";
  60873. };
  60874. __decorate([
  60875. BABYLON.serialize()
  60876. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  60877. __decorate([
  60878. BABYLON.serialize()
  60879. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60880. return FreeCameraGamepadInput;
  60881. }());
  60882. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  60883. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  60884. })(BABYLON || (BABYLON = {}));
  60885. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  60886. var BABYLON;
  60887. (function (BABYLON) {
  60888. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  60889. function ArcRotateCameraGamepadInput() {
  60890. this.gamepadRotationSensibility = 80;
  60891. this.gamepadMoveSensibility = 40;
  60892. }
  60893. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60894. var _this = this;
  60895. var manager = this.camera.getScene().gamepadManager;
  60896. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60897. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60898. // prioritize XBOX gamepads.
  60899. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60900. _this.gamepad = gamepad;
  60901. }
  60902. }
  60903. });
  60904. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60905. if (_this.gamepad === gamepad) {
  60906. _this.gamepad = null;
  60907. }
  60908. });
  60909. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60910. };
  60911. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  60912. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60913. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60914. this.gamepad = null;
  60915. };
  60916. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  60917. if (this.gamepad) {
  60918. var camera = this.camera;
  60919. var RSValues = this.gamepad.rightStick;
  60920. if (RSValues) {
  60921. if (RSValues.x != 0) {
  60922. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  60923. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  60924. camera.inertialAlphaOffset += normalizedRX;
  60925. }
  60926. }
  60927. if (RSValues.y != 0) {
  60928. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  60929. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  60930. camera.inertialBetaOffset += normalizedRY;
  60931. }
  60932. }
  60933. }
  60934. var LSValues = this.gamepad.leftStick;
  60935. if (LSValues && LSValues.y != 0) {
  60936. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60937. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  60938. this.camera.inertialRadiusOffset -= normalizedLY;
  60939. }
  60940. }
  60941. }
  60942. };
  60943. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  60944. return "ArcRotateCameraGamepadInput";
  60945. };
  60946. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  60947. return "gamepad";
  60948. };
  60949. __decorate([
  60950. BABYLON.serialize()
  60951. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  60952. __decorate([
  60953. BABYLON.serialize()
  60954. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60955. return ArcRotateCameraGamepadInput;
  60956. }());
  60957. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  60958. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  60959. })(BABYLON || (BABYLON = {}));
  60960. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  60961. var BABYLON;
  60962. (function (BABYLON) {
  60963. var GamepadManager = /** @class */ (function () {
  60964. function GamepadManager(_scene) {
  60965. var _this = this;
  60966. this._scene = _scene;
  60967. this._babylonGamepads = [];
  60968. this._oneGamepadConnected = false;
  60969. this._isMonitoring = false;
  60970. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  60971. if (!BABYLON.Tools.IsWindowObjectExist()) {
  60972. this._gamepadEventSupported = false;
  60973. }
  60974. else {
  60975. this._gamepadEventSupported = 'GamepadEvent' in window;
  60976. this._gamepadSupport = (navigator.getGamepads ||
  60977. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  60978. }
  60979. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  60980. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  60981. for (var i in _this._babylonGamepads) {
  60982. var gamepad = _this._babylonGamepads[i];
  60983. if (gamepad && gamepad._isConnected) {
  60984. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  60985. }
  60986. }
  60987. });
  60988. this._onGamepadConnectedEvent = function (evt) {
  60989. var gamepad = evt.gamepad;
  60990. if (gamepad.index in _this._babylonGamepads) {
  60991. if (_this._babylonGamepads[gamepad.index].isConnected) {
  60992. return;
  60993. }
  60994. }
  60995. var newGamepad;
  60996. if (_this._babylonGamepads[gamepad.index]) {
  60997. newGamepad = _this._babylonGamepads[gamepad.index];
  60998. newGamepad.browserGamepad = gamepad;
  60999. newGamepad._isConnected = true;
  61000. }
  61001. else {
  61002. newGamepad = _this._addNewGamepad(gamepad);
  61003. }
  61004. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  61005. _this._startMonitoringGamepads();
  61006. };
  61007. this._onGamepadDisconnectedEvent = function (evt) {
  61008. var gamepad = evt.gamepad;
  61009. // Remove the gamepad from the list of gamepads to monitor.
  61010. for (var i in _this._babylonGamepads) {
  61011. if (_this._babylonGamepads[i].index === gamepad.index) {
  61012. var disconnectedGamepad = _this._babylonGamepads[i];
  61013. disconnectedGamepad._isConnected = false;
  61014. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  61015. break;
  61016. }
  61017. }
  61018. };
  61019. if (this._gamepadSupport) {
  61020. //first add already-connected gamepads
  61021. this._updateGamepadObjects();
  61022. if (this._babylonGamepads.length) {
  61023. this._startMonitoringGamepads();
  61024. }
  61025. // Checking if the gamepad connected event is supported (like in Firefox)
  61026. if (this._gamepadEventSupported) {
  61027. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  61028. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  61029. }
  61030. else {
  61031. this._startMonitoringGamepads();
  61032. }
  61033. }
  61034. }
  61035. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  61036. get: function () {
  61037. return this._babylonGamepads;
  61038. },
  61039. enumerable: true,
  61040. configurable: true
  61041. });
  61042. GamepadManager.prototype.getGamepadByType = function (type) {
  61043. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  61044. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  61045. var gamepad = _a[_i];
  61046. if (gamepad && gamepad.type === type) {
  61047. return gamepad;
  61048. }
  61049. }
  61050. return null;
  61051. };
  61052. GamepadManager.prototype.dispose = function () {
  61053. if (this._gamepadEventSupported) {
  61054. if (this._onGamepadConnectedEvent) {
  61055. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  61056. }
  61057. if (this._onGamepadDisconnectedEvent) {
  61058. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  61059. }
  61060. this._onGamepadConnectedEvent = null;
  61061. this._onGamepadDisconnectedEvent = null;
  61062. }
  61063. this._babylonGamepads.forEach(function (gamepad) {
  61064. gamepad.dispose();
  61065. });
  61066. this.onGamepadConnectedObservable.clear();
  61067. this.onGamepadDisconnectedObservable.clear();
  61068. this._oneGamepadConnected = false;
  61069. this._stopMonitoringGamepads();
  61070. this._babylonGamepads = [];
  61071. };
  61072. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  61073. if (!this._oneGamepadConnected) {
  61074. this._oneGamepadConnected = true;
  61075. }
  61076. var newGamepad;
  61077. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  61078. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  61079. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  61080. }
  61081. else if (gamepad.pose) {
  61082. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  61083. }
  61084. else {
  61085. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  61086. }
  61087. this._babylonGamepads[newGamepad.index] = newGamepad;
  61088. return newGamepad;
  61089. };
  61090. GamepadManager.prototype._startMonitoringGamepads = function () {
  61091. if (!this._isMonitoring) {
  61092. this._isMonitoring = true;
  61093. //back-comp
  61094. if (!this._scene) {
  61095. this._checkGamepadsStatus();
  61096. }
  61097. }
  61098. };
  61099. GamepadManager.prototype._stopMonitoringGamepads = function () {
  61100. this._isMonitoring = false;
  61101. };
  61102. GamepadManager.prototype._checkGamepadsStatus = function () {
  61103. var _this = this;
  61104. // Hack to be compatible Chrome
  61105. this._updateGamepadObjects();
  61106. for (var i in this._babylonGamepads) {
  61107. var gamepad = this._babylonGamepads[i];
  61108. if (!gamepad || !gamepad.isConnected) {
  61109. continue;
  61110. }
  61111. gamepad.update();
  61112. }
  61113. if (this._isMonitoring && !this._scene) {
  61114. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  61115. }
  61116. };
  61117. // This function is called only on Chrome, which does not properly support
  61118. // connection/disconnection events and forces you to recopy again the gamepad object
  61119. GamepadManager.prototype._updateGamepadObjects = function () {
  61120. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  61121. for (var i = 0; i < gamepads.length; i++) {
  61122. if (gamepads[i]) {
  61123. if (!this._babylonGamepads[gamepads[i].index]) {
  61124. var newGamepad = this._addNewGamepad(gamepads[i]);
  61125. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  61126. }
  61127. else {
  61128. // Forced to copy again this object for Chrome for unknown reason
  61129. this._babylonGamepads[i].browserGamepad = gamepads[i];
  61130. if (!this._babylonGamepads[i].isConnected) {
  61131. this._babylonGamepads[i]._isConnected = true;
  61132. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  61133. }
  61134. }
  61135. }
  61136. }
  61137. };
  61138. return GamepadManager;
  61139. }());
  61140. BABYLON.GamepadManager = GamepadManager;
  61141. })(BABYLON || (BABYLON = {}));
  61142. //# sourceMappingURL=babylon.gamepadManager.js.map
  61143. var BABYLON;
  61144. (function (BABYLON) {
  61145. var StickValues = /** @class */ (function () {
  61146. function StickValues(x, y) {
  61147. this.x = x;
  61148. this.y = y;
  61149. }
  61150. return StickValues;
  61151. }());
  61152. BABYLON.StickValues = StickValues;
  61153. var Gamepad = /** @class */ (function () {
  61154. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  61155. if (leftStickX === void 0) { leftStickX = 0; }
  61156. if (leftStickY === void 0) { leftStickY = 1; }
  61157. if (rightStickX === void 0) { rightStickX = 2; }
  61158. if (rightStickY === void 0) { rightStickY = 3; }
  61159. this.id = id;
  61160. this.index = index;
  61161. this.browserGamepad = browserGamepad;
  61162. this._isConnected = true;
  61163. this._invertLeftStickY = false;
  61164. this.type = Gamepad.GAMEPAD;
  61165. this._leftStickAxisX = leftStickX;
  61166. this._leftStickAxisY = leftStickY;
  61167. this._rightStickAxisX = rightStickX;
  61168. this._rightStickAxisY = rightStickY;
  61169. if (this.browserGamepad.axes.length >= 2) {
  61170. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  61171. }
  61172. if (this.browserGamepad.axes.length >= 4) {
  61173. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  61174. }
  61175. }
  61176. Object.defineProperty(Gamepad.prototype, "isConnected", {
  61177. get: function () {
  61178. return this._isConnected;
  61179. },
  61180. enumerable: true,
  61181. configurable: true
  61182. });
  61183. Gamepad.prototype.onleftstickchanged = function (callback) {
  61184. this._onleftstickchanged = callback;
  61185. };
  61186. Gamepad.prototype.onrightstickchanged = function (callback) {
  61187. this._onrightstickchanged = callback;
  61188. };
  61189. Object.defineProperty(Gamepad.prototype, "leftStick", {
  61190. get: function () {
  61191. return this._leftStick;
  61192. },
  61193. set: function (newValues) {
  61194. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  61195. this._onleftstickchanged(newValues);
  61196. }
  61197. this._leftStick = newValues;
  61198. },
  61199. enumerable: true,
  61200. configurable: true
  61201. });
  61202. Object.defineProperty(Gamepad.prototype, "rightStick", {
  61203. get: function () {
  61204. return this._rightStick;
  61205. },
  61206. set: function (newValues) {
  61207. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  61208. this._onrightstickchanged(newValues);
  61209. }
  61210. this._rightStick = newValues;
  61211. },
  61212. enumerable: true,
  61213. configurable: true
  61214. });
  61215. Gamepad.prototype.update = function () {
  61216. if (this._leftStick) {
  61217. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  61218. if (this._invertLeftStickY) {
  61219. this.leftStick.y *= -1;
  61220. }
  61221. }
  61222. if (this._rightStick) {
  61223. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  61224. }
  61225. };
  61226. Gamepad.prototype.dispose = function () {
  61227. };
  61228. Gamepad.GAMEPAD = 0;
  61229. Gamepad.GENERIC = 1;
  61230. Gamepad.XBOX = 2;
  61231. Gamepad.POSE_ENABLED = 3;
  61232. return Gamepad;
  61233. }());
  61234. BABYLON.Gamepad = Gamepad;
  61235. var GenericPad = /** @class */ (function (_super) {
  61236. __extends(GenericPad, _super);
  61237. function GenericPad(id, index, browserGamepad) {
  61238. var _this = _super.call(this, id, index, browserGamepad) || this;
  61239. _this.onButtonDownObservable = new BABYLON.Observable();
  61240. _this.onButtonUpObservable = new BABYLON.Observable();
  61241. _this.type = Gamepad.GENERIC;
  61242. _this._buttons = new Array(browserGamepad.buttons.length);
  61243. return _this;
  61244. }
  61245. GenericPad.prototype.onbuttondown = function (callback) {
  61246. this._onbuttondown = callback;
  61247. };
  61248. GenericPad.prototype.onbuttonup = function (callback) {
  61249. this._onbuttonup = callback;
  61250. };
  61251. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  61252. if (newValue !== currentValue) {
  61253. if (newValue === 1) {
  61254. if (this._onbuttondown) {
  61255. this._onbuttondown(buttonIndex);
  61256. }
  61257. this.onButtonDownObservable.notifyObservers(buttonIndex);
  61258. }
  61259. if (newValue === 0) {
  61260. if (this._onbuttonup) {
  61261. this._onbuttonup(buttonIndex);
  61262. }
  61263. this.onButtonUpObservable.notifyObservers(buttonIndex);
  61264. }
  61265. }
  61266. return newValue;
  61267. };
  61268. GenericPad.prototype.update = function () {
  61269. _super.prototype.update.call(this);
  61270. for (var index = 0; index < this._buttons.length; index++) {
  61271. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  61272. }
  61273. };
  61274. GenericPad.prototype.dispose = function () {
  61275. _super.prototype.dispose.call(this);
  61276. this.onButtonDownObservable.clear();
  61277. this.onButtonUpObservable.clear();
  61278. };
  61279. return GenericPad;
  61280. }(Gamepad));
  61281. BABYLON.GenericPad = GenericPad;
  61282. })(BABYLON || (BABYLON = {}));
  61283. //# sourceMappingURL=babylon.gamepad.js.map
  61284. var BABYLON;
  61285. (function (BABYLON) {
  61286. var Xbox360Button;
  61287. (function (Xbox360Button) {
  61288. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  61289. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  61290. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  61291. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  61292. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  61293. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  61294. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  61295. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  61296. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  61297. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  61298. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  61299. var Xbox360Dpad;
  61300. (function (Xbox360Dpad) {
  61301. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  61302. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  61303. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  61304. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  61305. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  61306. var Xbox360Pad = /** @class */ (function (_super) {
  61307. __extends(Xbox360Pad, _super);
  61308. function Xbox360Pad(id, index, gamepad, xboxOne) {
  61309. if (xboxOne === void 0) { xboxOne = false; }
  61310. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  61311. _this._leftTrigger = 0;
  61312. _this._rightTrigger = 0;
  61313. _this.onButtonDownObservable = new BABYLON.Observable();
  61314. _this.onButtonUpObservable = new BABYLON.Observable();
  61315. _this.onPadDownObservable = new BABYLON.Observable();
  61316. _this.onPadUpObservable = new BABYLON.Observable();
  61317. _this._buttonA = 0;
  61318. _this._buttonB = 0;
  61319. _this._buttonX = 0;
  61320. _this._buttonY = 0;
  61321. _this._buttonBack = 0;
  61322. _this._buttonStart = 0;
  61323. _this._buttonLB = 0;
  61324. _this._buttonRB = 0;
  61325. _this._buttonLeftStick = 0;
  61326. _this._buttonRightStick = 0;
  61327. _this._dPadUp = 0;
  61328. _this._dPadDown = 0;
  61329. _this._dPadLeft = 0;
  61330. _this._dPadRight = 0;
  61331. _this._isXboxOnePad = false;
  61332. _this.type = BABYLON.Gamepad.XBOX;
  61333. _this._isXboxOnePad = xboxOne;
  61334. return _this;
  61335. }
  61336. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  61337. this._onlefttriggerchanged = callback;
  61338. };
  61339. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  61340. this._onrighttriggerchanged = callback;
  61341. };
  61342. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  61343. get: function () {
  61344. return this._leftTrigger;
  61345. },
  61346. set: function (newValue) {
  61347. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  61348. this._onlefttriggerchanged(newValue);
  61349. }
  61350. this._leftTrigger = newValue;
  61351. },
  61352. enumerable: true,
  61353. configurable: true
  61354. });
  61355. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  61356. get: function () {
  61357. return this._rightTrigger;
  61358. },
  61359. set: function (newValue) {
  61360. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  61361. this._onrighttriggerchanged(newValue);
  61362. }
  61363. this._rightTrigger = newValue;
  61364. },
  61365. enumerable: true,
  61366. configurable: true
  61367. });
  61368. Xbox360Pad.prototype.onbuttondown = function (callback) {
  61369. this._onbuttondown = callback;
  61370. };
  61371. Xbox360Pad.prototype.onbuttonup = function (callback) {
  61372. this._onbuttonup = callback;
  61373. };
  61374. Xbox360Pad.prototype.ondpaddown = function (callback) {
  61375. this._ondpaddown = callback;
  61376. };
  61377. Xbox360Pad.prototype.ondpadup = function (callback) {
  61378. this._ondpadup = callback;
  61379. };
  61380. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  61381. if (newValue !== currentValue) {
  61382. if (newValue === 1) {
  61383. if (this._onbuttondown) {
  61384. this._onbuttondown(buttonType);
  61385. }
  61386. this.onButtonDownObservable.notifyObservers(buttonType);
  61387. }
  61388. if (newValue === 0) {
  61389. if (this._onbuttonup) {
  61390. this._onbuttonup(buttonType);
  61391. }
  61392. this.onButtonUpObservable.notifyObservers(buttonType);
  61393. }
  61394. }
  61395. return newValue;
  61396. };
  61397. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  61398. if (newValue !== currentValue) {
  61399. if (newValue === 1) {
  61400. if (this._ondpaddown) {
  61401. this._ondpaddown(buttonType);
  61402. }
  61403. this.onPadDownObservable.notifyObservers(buttonType);
  61404. }
  61405. if (newValue === 0) {
  61406. if (this._ondpadup) {
  61407. this._ondpadup(buttonType);
  61408. }
  61409. this.onPadUpObservable.notifyObservers(buttonType);
  61410. }
  61411. }
  61412. return newValue;
  61413. };
  61414. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  61415. get: function () {
  61416. return this._buttonA;
  61417. },
  61418. set: function (value) {
  61419. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  61420. },
  61421. enumerable: true,
  61422. configurable: true
  61423. });
  61424. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  61425. get: function () {
  61426. return this._buttonB;
  61427. },
  61428. set: function (value) {
  61429. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  61430. },
  61431. enumerable: true,
  61432. configurable: true
  61433. });
  61434. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  61435. get: function () {
  61436. return this._buttonX;
  61437. },
  61438. set: function (value) {
  61439. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  61440. },
  61441. enumerable: true,
  61442. configurable: true
  61443. });
  61444. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  61445. get: function () {
  61446. return this._buttonY;
  61447. },
  61448. set: function (value) {
  61449. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  61450. },
  61451. enumerable: true,
  61452. configurable: true
  61453. });
  61454. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  61455. get: function () {
  61456. return this._buttonStart;
  61457. },
  61458. set: function (value) {
  61459. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  61460. },
  61461. enumerable: true,
  61462. configurable: true
  61463. });
  61464. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  61465. get: function () {
  61466. return this._buttonBack;
  61467. },
  61468. set: function (value) {
  61469. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  61470. },
  61471. enumerable: true,
  61472. configurable: true
  61473. });
  61474. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  61475. get: function () {
  61476. return this._buttonLB;
  61477. },
  61478. set: function (value) {
  61479. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  61480. },
  61481. enumerable: true,
  61482. configurable: true
  61483. });
  61484. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  61485. get: function () {
  61486. return this._buttonRB;
  61487. },
  61488. set: function (value) {
  61489. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  61490. },
  61491. enumerable: true,
  61492. configurable: true
  61493. });
  61494. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  61495. get: function () {
  61496. return this._buttonLeftStick;
  61497. },
  61498. set: function (value) {
  61499. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  61500. },
  61501. enumerable: true,
  61502. configurable: true
  61503. });
  61504. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  61505. get: function () {
  61506. return this._buttonRightStick;
  61507. },
  61508. set: function (value) {
  61509. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  61510. },
  61511. enumerable: true,
  61512. configurable: true
  61513. });
  61514. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  61515. get: function () {
  61516. return this._dPadUp;
  61517. },
  61518. set: function (value) {
  61519. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  61520. },
  61521. enumerable: true,
  61522. configurable: true
  61523. });
  61524. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  61525. get: function () {
  61526. return this._dPadDown;
  61527. },
  61528. set: function (value) {
  61529. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  61530. },
  61531. enumerable: true,
  61532. configurable: true
  61533. });
  61534. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  61535. get: function () {
  61536. return this._dPadLeft;
  61537. },
  61538. set: function (value) {
  61539. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  61540. },
  61541. enumerable: true,
  61542. configurable: true
  61543. });
  61544. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  61545. get: function () {
  61546. return this._dPadRight;
  61547. },
  61548. set: function (value) {
  61549. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  61550. },
  61551. enumerable: true,
  61552. configurable: true
  61553. });
  61554. Xbox360Pad.prototype.update = function () {
  61555. _super.prototype.update.call(this);
  61556. if (this._isXboxOnePad) {
  61557. this.buttonA = this.browserGamepad.buttons[0].value;
  61558. this.buttonB = this.browserGamepad.buttons[1].value;
  61559. this.buttonX = this.browserGamepad.buttons[2].value;
  61560. this.buttonY = this.browserGamepad.buttons[3].value;
  61561. this.buttonLB = this.browserGamepad.buttons[4].value;
  61562. this.buttonRB = this.browserGamepad.buttons[5].value;
  61563. this.leftTrigger = this.browserGamepad.axes[2];
  61564. this.rightTrigger = this.browserGamepad.axes[5];
  61565. this.buttonBack = this.browserGamepad.buttons[9].value;
  61566. this.buttonStart = this.browserGamepad.buttons[8].value;
  61567. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  61568. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  61569. this.dPadUp = this.browserGamepad.buttons[11].value;
  61570. this.dPadDown = this.browserGamepad.buttons[12].value;
  61571. this.dPadLeft = this.browserGamepad.buttons[13].value;
  61572. this.dPadRight = this.browserGamepad.buttons[14].value;
  61573. }
  61574. else {
  61575. this.buttonA = this.browserGamepad.buttons[0].value;
  61576. this.buttonB = this.browserGamepad.buttons[1].value;
  61577. this.buttonX = this.browserGamepad.buttons[2].value;
  61578. this.buttonY = this.browserGamepad.buttons[3].value;
  61579. this.buttonLB = this.browserGamepad.buttons[4].value;
  61580. this.buttonRB = this.browserGamepad.buttons[5].value;
  61581. this.leftTrigger = this.browserGamepad.buttons[6].value;
  61582. this.rightTrigger = this.browserGamepad.buttons[7].value;
  61583. this.buttonBack = this.browserGamepad.buttons[8].value;
  61584. this.buttonStart = this.browserGamepad.buttons[9].value;
  61585. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  61586. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  61587. this.dPadUp = this.browserGamepad.buttons[12].value;
  61588. this.dPadDown = this.browserGamepad.buttons[13].value;
  61589. this.dPadLeft = this.browserGamepad.buttons[14].value;
  61590. this.dPadRight = this.browserGamepad.buttons[15].value;
  61591. }
  61592. };
  61593. Xbox360Pad.prototype.dispose = function () {
  61594. _super.prototype.dispose.call(this);
  61595. this.onButtonDownObservable.clear();
  61596. this.onButtonUpObservable.clear();
  61597. this.onPadDownObservable.clear();
  61598. this.onPadUpObservable.clear();
  61599. };
  61600. return Xbox360Pad;
  61601. }(BABYLON.Gamepad));
  61602. BABYLON.Xbox360Pad = Xbox360Pad;
  61603. })(BABYLON || (BABYLON = {}));
  61604. //# sourceMappingURL=babylon.xboxGamepad.js.map
  61605. var BABYLON;
  61606. (function (BABYLON) {
  61607. var PoseEnabledControllerType;
  61608. (function (PoseEnabledControllerType) {
  61609. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  61610. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  61611. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  61612. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  61613. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  61614. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  61615. var PoseEnabledControllerHelper = /** @class */ (function () {
  61616. function PoseEnabledControllerHelper() {
  61617. }
  61618. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  61619. // Oculus Touch
  61620. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  61621. return new BABYLON.OculusTouchController(vrGamepad);
  61622. }
  61623. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  61624. return new BABYLON.WindowsMotionController(vrGamepad);
  61625. }
  61626. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  61627. return new BABYLON.ViveController(vrGamepad);
  61628. }
  61629. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  61630. return new BABYLON.GearVRController(vrGamepad);
  61631. }
  61632. else {
  61633. return new BABYLON.GenericController(vrGamepad);
  61634. }
  61635. };
  61636. return PoseEnabledControllerHelper;
  61637. }());
  61638. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  61639. var PoseEnabledController = /** @class */ (function (_super) {
  61640. __extends(PoseEnabledController, _super);
  61641. function PoseEnabledController(browserGamepad) {
  61642. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  61643. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  61644. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  61645. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  61646. // Represents device position and rotation in babylon space
  61647. _this.devicePosition = BABYLON.Vector3.Zero();
  61648. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  61649. _this.deviceScaleFactor = 1;
  61650. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  61651. _this._deviceToWorld = BABYLON.Matrix.Identity();
  61652. _this._workingMatrix = BABYLON.Matrix.Identity();
  61653. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  61654. _this.controllerType = PoseEnabledControllerType.GENERIC;
  61655. _this.position = BABYLON.Vector3.Zero();
  61656. _this.rotationQuaternion = new BABYLON.Quaternion();
  61657. _this._calculatedPosition = BABYLON.Vector3.Zero();
  61658. _this._calculatedRotation = new BABYLON.Quaternion();
  61659. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  61660. return _this;
  61661. }
  61662. PoseEnabledController.prototype.update = function () {
  61663. _super.prototype.update.call(this);
  61664. var pose = this.browserGamepad.pose;
  61665. this.updateFromDevice(pose);
  61666. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  61667. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  61668. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  61669. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  61670. if (this._mesh) {
  61671. this._mesh.position.copyFrom(this.devicePosition);
  61672. if (this._mesh.rotationQuaternion) {
  61673. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  61674. }
  61675. }
  61676. };
  61677. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  61678. if (poseData) {
  61679. this.rawPose = poseData;
  61680. if (poseData.position) {
  61681. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  61682. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  61683. this._deviceRoomPosition.z *= -1;
  61684. }
  61685. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  61686. this._calculatedPosition.addInPlace(this.position);
  61687. }
  61688. var pose = this.rawPose;
  61689. if (poseData.orientation && pose.orientation) {
  61690. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  61691. if (this._mesh) {
  61692. if (this._mesh.getScene().useRightHandedSystem) {
  61693. this._deviceRoomRotationQuaternion.z *= -1;
  61694. this._deviceRoomRotationQuaternion.w *= -1;
  61695. }
  61696. else {
  61697. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  61698. }
  61699. }
  61700. // if the camera is set, rotate to the camera's rotation
  61701. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  61702. }
  61703. }
  61704. };
  61705. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  61706. if (this._mesh) {
  61707. this._mesh.parent = null;
  61708. }
  61709. this._mesh = mesh;
  61710. if (this._poseControlledCamera) {
  61711. this._mesh.parent = this._poseControlledCamera;
  61712. }
  61713. if (!this._mesh.rotationQuaternion) {
  61714. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  61715. }
  61716. };
  61717. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  61718. this._poseControlledCamera = camera;
  61719. if (this._mesh) {
  61720. this._mesh.parent = this._poseControlledCamera;
  61721. }
  61722. };
  61723. PoseEnabledController.prototype.dispose = function () {
  61724. if (this._mesh) {
  61725. this._mesh.dispose();
  61726. }
  61727. this._mesh = null;
  61728. _super.prototype.dispose.call(this);
  61729. };
  61730. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  61731. get: function () {
  61732. return this._mesh;
  61733. },
  61734. enumerable: true,
  61735. configurable: true
  61736. });
  61737. PoseEnabledController.prototype.getForwardRay = function (length) {
  61738. if (length === void 0) { length = 100; }
  61739. if (!this.mesh) {
  61740. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  61741. }
  61742. var m = this.mesh.getWorldMatrix();
  61743. var origin = m.getTranslation();
  61744. var forward = new BABYLON.Vector3(0, 0, -1);
  61745. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61746. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61747. return new BABYLON.Ray(origin, direction, length);
  61748. };
  61749. return PoseEnabledController;
  61750. }(BABYLON.Gamepad));
  61751. BABYLON.PoseEnabledController = PoseEnabledController;
  61752. })(BABYLON || (BABYLON = {}));
  61753. //# sourceMappingURL=babylon.poseEnabledController.js.map
  61754. var BABYLON;
  61755. (function (BABYLON) {
  61756. var WebVRController = /** @class */ (function (_super) {
  61757. __extends(WebVRController, _super);
  61758. function WebVRController(vrGamepad) {
  61759. var _this = _super.call(this, vrGamepad) || this;
  61760. // Observables
  61761. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  61762. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  61763. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  61764. _this.onPadStateChangedObservable = new BABYLON.Observable();
  61765. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  61766. _this.pad = { x: 0, y: 0 };
  61767. // avoid GC, store state in a tmp object
  61768. _this._changes = {
  61769. pressChanged: false,
  61770. touchChanged: false,
  61771. valueChanged: false,
  61772. changed: false
  61773. };
  61774. _this._buttons = new Array(vrGamepad.buttons.length);
  61775. _this.hand = vrGamepad.hand;
  61776. return _this;
  61777. }
  61778. WebVRController.prototype.onButtonStateChange = function (callback) {
  61779. this._onButtonStateChange = callback;
  61780. };
  61781. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  61782. get: function () {
  61783. return this._defaultModel;
  61784. },
  61785. enumerable: true,
  61786. configurable: true
  61787. });
  61788. WebVRController.prototype.update = function () {
  61789. _super.prototype.update.call(this);
  61790. for (var index = 0; index < this._buttons.length; index++) {
  61791. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  61792. }
  61793. ;
  61794. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  61795. this.pad.x = this.leftStick.x;
  61796. this.pad.y = this.leftStick.y;
  61797. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  61798. }
  61799. };
  61800. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  61801. if (!newState) {
  61802. newState = {
  61803. pressed: false,
  61804. touched: false,
  61805. value: 0
  61806. };
  61807. }
  61808. if (!currentState) {
  61809. this._buttons[buttonIndex] = {
  61810. pressed: newState.pressed,
  61811. touched: newState.touched,
  61812. value: newState.value
  61813. };
  61814. return;
  61815. }
  61816. this._checkChanges(newState, currentState);
  61817. if (this._changes.changed) {
  61818. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  61819. this.handleButtonChange(buttonIndex, newState, this._changes);
  61820. }
  61821. this._buttons[buttonIndex].pressed = newState.pressed;
  61822. this._buttons[buttonIndex].touched = newState.touched;
  61823. // oculus triggers are never 0, thou not touched.
  61824. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  61825. };
  61826. WebVRController.prototype._checkChanges = function (newState, currentState) {
  61827. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  61828. this._changes.touchChanged = newState.touched !== currentState.touched;
  61829. this._changes.valueChanged = newState.value !== currentState.value;
  61830. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  61831. return this._changes;
  61832. };
  61833. WebVRController.prototype.dispose = function () {
  61834. _super.prototype.dispose.call(this);
  61835. this.onTriggerStateChangedObservable.clear();
  61836. this.onMainButtonStateChangedObservable.clear();
  61837. this.onSecondaryButtonStateChangedObservable.clear();
  61838. this.onPadStateChangedObservable.clear();
  61839. this.onPadValuesChangedObservable.clear();
  61840. };
  61841. return WebVRController;
  61842. }(BABYLON.PoseEnabledController));
  61843. BABYLON.WebVRController = WebVRController;
  61844. })(BABYLON || (BABYLON = {}));
  61845. //# sourceMappingURL=babylon.webVRController.js.map
  61846. var BABYLON;
  61847. (function (BABYLON) {
  61848. var OculusTouchController = /** @class */ (function (_super) {
  61849. __extends(OculusTouchController, _super);
  61850. function OculusTouchController(vrGamepad) {
  61851. var _this = _super.call(this, vrGamepad) || this;
  61852. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  61853. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  61854. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  61855. return _this;
  61856. }
  61857. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61858. var _this = this;
  61859. var meshName;
  61860. // Hand
  61861. if (this.hand === 'left') {
  61862. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  61863. }
  61864. else {
  61865. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  61866. }
  61867. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  61868. /*
  61869. Parent Mesh name: oculus_touch_left
  61870. - body
  61871. - trigger
  61872. - thumbstick
  61873. - grip
  61874. - button_y
  61875. - button_x
  61876. - button_enter
  61877. */
  61878. _this._defaultModel = newMeshes[1];
  61879. _this.attachToMesh(_this._defaultModel);
  61880. if (meshLoaded) {
  61881. meshLoaded(_this._defaultModel);
  61882. }
  61883. });
  61884. };
  61885. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  61886. // helper getters for left and right hand.
  61887. get: function () {
  61888. if (this.hand === 'right') {
  61889. return this.onMainButtonStateChangedObservable;
  61890. }
  61891. else {
  61892. throw new Error('No A button on left hand');
  61893. }
  61894. },
  61895. enumerable: true,
  61896. configurable: true
  61897. });
  61898. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  61899. get: function () {
  61900. if (this.hand === 'right') {
  61901. return this.onSecondaryButtonStateChangedObservable;
  61902. }
  61903. else {
  61904. throw new Error('No B button on left hand');
  61905. }
  61906. },
  61907. enumerable: true,
  61908. configurable: true
  61909. });
  61910. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  61911. get: function () {
  61912. if (this.hand === 'left') {
  61913. return this.onMainButtonStateChangedObservable;
  61914. }
  61915. else {
  61916. throw new Error('No X button on right hand');
  61917. }
  61918. },
  61919. enumerable: true,
  61920. configurable: true
  61921. });
  61922. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  61923. get: function () {
  61924. if (this.hand === 'left') {
  61925. return this.onSecondaryButtonStateChangedObservable;
  61926. }
  61927. else {
  61928. throw new Error('No Y button on right hand');
  61929. }
  61930. },
  61931. enumerable: true,
  61932. configurable: true
  61933. });
  61934. /*
  61935. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  61936. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  61937. 2) secondary trigger (same)
  61938. 3) A (right) X (left), touch, pressed = value
  61939. 4) B / Y
  61940. 5) thumb rest
  61941. */
  61942. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61943. var notifyObject = state; //{ state: state, changes: changes };
  61944. var triggerDirection = this.hand === 'right' ? -1 : 1;
  61945. switch (buttonIdx) {
  61946. case 0:
  61947. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61948. return;
  61949. case 1:// index trigger
  61950. if (this._defaultModel) {
  61951. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  61952. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  61953. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  61954. }
  61955. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61956. return;
  61957. case 2:// secondary trigger
  61958. if (this._defaultModel) {
  61959. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  61960. }
  61961. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  61962. return;
  61963. case 3:
  61964. if (this._defaultModel) {
  61965. if (notifyObject.pressed) {
  61966. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  61967. }
  61968. else {
  61969. (this._defaultModel.getChildren()[1]).position.y = 0;
  61970. }
  61971. }
  61972. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61973. return;
  61974. case 4:
  61975. if (this._defaultModel) {
  61976. if (notifyObject.pressed) {
  61977. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61978. }
  61979. else {
  61980. (this._defaultModel.getChildren()[2]).position.y = 0;
  61981. }
  61982. }
  61983. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61984. return;
  61985. case 5:
  61986. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  61987. return;
  61988. }
  61989. };
  61990. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  61991. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  61992. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  61993. return OculusTouchController;
  61994. }(BABYLON.WebVRController));
  61995. BABYLON.OculusTouchController = OculusTouchController;
  61996. })(BABYLON || (BABYLON = {}));
  61997. //# sourceMappingURL=babylon.oculusTouchController.js.map
  61998. var BABYLON;
  61999. (function (BABYLON) {
  62000. var ViveController = /** @class */ (function (_super) {
  62001. __extends(ViveController, _super);
  62002. function ViveController(vrGamepad) {
  62003. var _this = _super.call(this, vrGamepad) || this;
  62004. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  62005. _this._invertLeftStickY = true;
  62006. return _this;
  62007. }
  62008. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  62009. var _this = this;
  62010. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  62011. /*
  62012. Parent Mesh name: ViveWand
  62013. - body
  62014. - r_gripper
  62015. - l_gripper
  62016. - menu_button
  62017. - system_button
  62018. - trackpad
  62019. - trigger
  62020. - LED
  62021. */
  62022. _this._defaultModel = newMeshes[1];
  62023. _this.attachToMesh(_this._defaultModel);
  62024. if (meshLoaded) {
  62025. meshLoaded(_this._defaultModel);
  62026. }
  62027. });
  62028. };
  62029. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  62030. get: function () {
  62031. return this.onMainButtonStateChangedObservable;
  62032. },
  62033. enumerable: true,
  62034. configurable: true
  62035. });
  62036. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  62037. get: function () {
  62038. return this.onMainButtonStateChangedObservable;
  62039. },
  62040. enumerable: true,
  62041. configurable: true
  62042. });
  62043. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  62044. get: function () {
  62045. return this.onSecondaryButtonStateChangedObservable;
  62046. },
  62047. enumerable: true,
  62048. configurable: true
  62049. });
  62050. /**
  62051. * Vive mapping:
  62052. * 0: touchpad
  62053. * 1: trigger
  62054. * 2: left AND right buttons
  62055. * 3: menu button
  62056. */
  62057. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  62058. var notifyObject = state; //{ state: state, changes: changes };
  62059. switch (buttonIdx) {
  62060. case 0:
  62061. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  62062. return;
  62063. case 1:// index trigger
  62064. if (this._defaultModel) {
  62065. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  62066. }
  62067. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  62068. return;
  62069. case 2:// left AND right button
  62070. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  62071. return;
  62072. case 3:
  62073. if (this._defaultModel) {
  62074. if (notifyObject.pressed) {
  62075. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  62076. }
  62077. else {
  62078. (this._defaultModel.getChildren()[2]).position.y = 0;
  62079. }
  62080. }
  62081. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  62082. return;
  62083. }
  62084. };
  62085. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  62086. ViveController.MODEL_FILENAME = 'wand.babylon';
  62087. return ViveController;
  62088. }(BABYLON.WebVRController));
  62089. BABYLON.ViveController = ViveController;
  62090. })(BABYLON || (BABYLON = {}));
  62091. //# sourceMappingURL=babylon.viveController.js.map
  62092. var BABYLON;
  62093. (function (BABYLON) {
  62094. var GenericController = /** @class */ (function (_super) {
  62095. __extends(GenericController, _super);
  62096. function GenericController(vrGamepad) {
  62097. return _super.call(this, vrGamepad) || this;
  62098. }
  62099. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  62100. var _this = this;
  62101. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  62102. _this._defaultModel = newMeshes[1];
  62103. _this.attachToMesh(_this._defaultModel);
  62104. if (meshLoaded) {
  62105. meshLoaded(_this._defaultModel);
  62106. }
  62107. });
  62108. };
  62109. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  62110. console.log("Button id: " + buttonIdx + "state: ");
  62111. console.dir(state);
  62112. };
  62113. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  62114. GenericController.MODEL_FILENAME = 'generic.babylon';
  62115. return GenericController;
  62116. }(BABYLON.WebVRController));
  62117. BABYLON.GenericController = GenericController;
  62118. })(BABYLON || (BABYLON = {}));
  62119. //# sourceMappingURL=babylon.genericController.js.map
  62120. var BABYLON;
  62121. (function (BABYLON) {
  62122. var LoadedMeshInfo = /** @class */ (function () {
  62123. function LoadedMeshInfo() {
  62124. this.buttonMeshes = {};
  62125. this.axisMeshes = {};
  62126. }
  62127. return LoadedMeshInfo;
  62128. }());
  62129. var WindowsMotionController = /** @class */ (function (_super) {
  62130. __extends(WindowsMotionController, _super);
  62131. function WindowsMotionController(vrGamepad) {
  62132. var _this = _super.call(this, vrGamepad) || this;
  62133. _this._mapping = {
  62134. // Semantic button names
  62135. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  62136. // A mapping of the button name to glTF model node name
  62137. // that should be transformed by button value.
  62138. buttonMeshNames: {
  62139. 'trigger': 'SELECT',
  62140. 'menu': 'MENU',
  62141. 'grip': 'GRASP',
  62142. 'thumbstick': 'THUMBSTICK_PRESS',
  62143. 'trackpad': 'TOUCHPAD_PRESS'
  62144. },
  62145. // This mapping is used to translate from the Motion Controller to Babylon semantics
  62146. buttonObservableNames: {
  62147. 'trigger': 'onTriggerStateChangedObservable',
  62148. 'menu': 'onSecondaryButtonStateChangedObservable',
  62149. 'grip': 'onMainButtonStateChangedObservable',
  62150. 'thumbstick': 'onPadStateChangedObservable',
  62151. 'trackpad': 'onTrackpadChangedObservable'
  62152. },
  62153. // A mapping of the axis name to glTF model node name
  62154. // that should be transformed by axis value.
  62155. // This array mirrors the browserGamepad.axes array, such that
  62156. // the mesh corresponding to axis 0 is in this array index 0.
  62157. axisMeshNames: [
  62158. 'THUMBSTICK_X',
  62159. 'THUMBSTICK_Y',
  62160. 'TOUCHPAD_TOUCH_X',
  62161. 'TOUCHPAD_TOUCH_Y'
  62162. ],
  62163. pointingPoseMeshName: 'POINTING_POSE'
  62164. };
  62165. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  62166. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  62167. _this.trackpad = { x: 0, y: 0 };
  62168. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  62169. _this._loadedMeshInfo = null;
  62170. return _this;
  62171. }
  62172. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  62173. get: function () {
  62174. return this.onTriggerStateChangedObservable;
  62175. },
  62176. enumerable: true,
  62177. configurable: true
  62178. });
  62179. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  62180. get: function () {
  62181. return this.onSecondaryButtonStateChangedObservable;
  62182. },
  62183. enumerable: true,
  62184. configurable: true
  62185. });
  62186. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  62187. get: function () {
  62188. return this.onMainButtonStateChangedObservable;
  62189. },
  62190. enumerable: true,
  62191. configurable: true
  62192. });
  62193. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  62194. get: function () {
  62195. return this.onPadStateChangedObservable;
  62196. },
  62197. enumerable: true,
  62198. configurable: true
  62199. });
  62200. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  62201. get: function () {
  62202. return this.onTrackpadChangedObservable;
  62203. },
  62204. enumerable: true,
  62205. configurable: true
  62206. });
  62207. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  62208. get: function () {
  62209. return this.onTrackpadValuesChangedObservable;
  62210. },
  62211. enumerable: true,
  62212. configurable: true
  62213. });
  62214. /**
  62215. * Called once per frame by the engine.
  62216. */
  62217. WindowsMotionController.prototype.update = function () {
  62218. _super.prototype.update.call(this);
  62219. // Only need to animate axes if there is a loaded mesh
  62220. if (this._loadedMeshInfo) {
  62221. if (this.browserGamepad.axes) {
  62222. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  62223. this.trackpad.x = this.browserGamepad["axes"][2];
  62224. this.trackpad.y = this.browserGamepad["axes"][3];
  62225. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  62226. }
  62227. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  62228. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  62229. }
  62230. }
  62231. }
  62232. };
  62233. /**
  62234. * Called once for each button that changed state since the last frame
  62235. * @param buttonIdx Which button index changed
  62236. * @param state New state of the button
  62237. * @param changes Which properties on the state changed since last frame
  62238. */
  62239. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  62240. var buttonName = this._mapping.buttons[buttonIdx];
  62241. if (!buttonName) {
  62242. return;
  62243. }
  62244. // Only emit events for buttons that we know how to map from index to name
  62245. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  62246. if (observable) {
  62247. observable.notifyObservers(state);
  62248. }
  62249. this.lerpButtonTransform(buttonName, state.value);
  62250. };
  62251. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  62252. // If there is no loaded mesh, there is nothing to transform.
  62253. if (!this._loadedMeshInfo) {
  62254. return;
  62255. }
  62256. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  62257. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  62258. return;
  62259. }
  62260. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  62261. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  62262. };
  62263. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  62264. if (!this._loadedMeshInfo) {
  62265. return;
  62266. }
  62267. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  62268. if (!meshInfo) {
  62269. return;
  62270. }
  62271. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  62272. return;
  62273. }
  62274. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  62275. var lerpValue = axisValue * 0.5 + 0.5;
  62276. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  62277. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  62278. };
  62279. /**
  62280. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  62281. * @param scene scene in which to add meshes
  62282. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  62283. */
  62284. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  62285. var _this = this;
  62286. if (forceDefault === void 0) { forceDefault = false; }
  62287. var path;
  62288. var filename;
  62289. // Checking if GLB loader is present
  62290. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  62291. // Determine the device specific folder based on the ID suffix
  62292. var device = 'default';
  62293. if (this.id && !forceDefault) {
  62294. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  62295. device = ((match && match[0]) || device);
  62296. }
  62297. // Hand
  62298. if (this.hand === 'left') {
  62299. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  62300. }
  62301. else {
  62302. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  62303. }
  62304. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  62305. }
  62306. else {
  62307. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  62308. path = BABYLON.GenericController.MODEL_BASE_URL;
  62309. filename = BABYLON.GenericController.MODEL_FILENAME;
  62310. }
  62311. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  62312. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  62313. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  62314. if (!_this._loadedMeshInfo) {
  62315. return;
  62316. }
  62317. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  62318. _this.attachToMesh(_this._defaultModel);
  62319. if (meshLoaded) {
  62320. meshLoaded(_this._defaultModel);
  62321. }
  62322. }, null, function (scene, message) {
  62323. BABYLON.Tools.Log(message);
  62324. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  62325. if (!forceDefault) {
  62326. _this.initControllerMesh(scene, meshLoaded, true);
  62327. }
  62328. });
  62329. };
  62330. /**
  62331. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  62332. * can be transformed by button presses and axes values, based on this._mapping.
  62333. *
  62334. * @param scene scene in which the meshes exist
  62335. * @param meshes list of meshes that make up the controller model to process
  62336. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  62337. */
  62338. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  62339. var loadedMeshInfo = null;
  62340. // Create a new mesh to contain the glTF hierarchy
  62341. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  62342. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  62343. var childMesh = null;
  62344. for (var i = 0; i < meshes.length; i++) {
  62345. var mesh = meshes[i];
  62346. if (!mesh.parent) {
  62347. // Exclude controller meshes from picking results
  62348. mesh.isPickable = false;
  62349. // Handle root node, attach to the new parentMesh
  62350. childMesh = mesh;
  62351. break;
  62352. }
  62353. }
  62354. if (childMesh) {
  62355. childMesh.setParent(parentMesh);
  62356. // Create our mesh info. Note that this method will always return non-null.
  62357. loadedMeshInfo = this.createMeshInfo(parentMesh);
  62358. }
  62359. else {
  62360. BABYLON.Tools.Warn('Could not find root node in model file.');
  62361. }
  62362. return loadedMeshInfo;
  62363. };
  62364. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  62365. var loadedMeshInfo = new LoadedMeshInfo();
  62366. var i;
  62367. loadedMeshInfo.rootNode = rootNode;
  62368. // Reset the caches
  62369. loadedMeshInfo.buttonMeshes = {};
  62370. loadedMeshInfo.axisMeshes = {};
  62371. // Button Meshes
  62372. for (i = 0; i < this._mapping.buttons.length; i++) {
  62373. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  62374. if (!buttonMeshName) {
  62375. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  62376. continue;
  62377. }
  62378. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  62379. if (!buttonMesh) {
  62380. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  62381. continue;
  62382. }
  62383. var buttonMeshInfo = {
  62384. index: i,
  62385. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  62386. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  62387. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  62388. };
  62389. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  62390. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  62391. }
  62392. else {
  62393. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  62394. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  62395. '(VALUE: ' + !!buttonMeshInfo.value +
  62396. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  62397. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  62398. ')');
  62399. }
  62400. }
  62401. // Axis Meshes
  62402. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  62403. var axisMeshName = this._mapping.axisMeshNames[i];
  62404. if (!axisMeshName) {
  62405. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  62406. continue;
  62407. }
  62408. var axisMesh = getChildByName(rootNode, axisMeshName);
  62409. if (!axisMesh) {
  62410. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  62411. continue;
  62412. }
  62413. var axisMeshInfo = {
  62414. index: i,
  62415. value: getImmediateChildByName(axisMesh, 'VALUE'),
  62416. min: getImmediateChildByName(axisMesh, 'MIN'),
  62417. max: getImmediateChildByName(axisMesh, 'MAX')
  62418. };
  62419. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  62420. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  62421. }
  62422. else {
  62423. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  62424. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  62425. '(VALUE: ' + !!axisMeshInfo.value +
  62426. ', MIN: ' + !!axisMeshInfo.min +
  62427. ', MAX:' + !!axisMeshInfo.max +
  62428. ')');
  62429. }
  62430. }
  62431. // Pointing Ray
  62432. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  62433. if (!loadedMeshInfo.pointingPoseNode) {
  62434. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  62435. }
  62436. return loadedMeshInfo;
  62437. // Look through all children recursively. This will return null if no mesh exists with the given name.
  62438. function getChildByName(node, name) {
  62439. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  62440. }
  62441. // Look through only immediate children. This will return null if no mesh exists with the given name.
  62442. function getImmediateChildByName(node, name) {
  62443. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  62444. }
  62445. };
  62446. WindowsMotionController.prototype.getForwardRay = function (length) {
  62447. if (length === void 0) { length = 100; }
  62448. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  62449. return _super.prototype.getForwardRay.call(this, length);
  62450. }
  62451. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  62452. var origin = m.getTranslation();
  62453. var forward = new BABYLON.Vector3(0, 0, -1);
  62454. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  62455. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  62456. return new BABYLON.Ray(origin, direction, length);
  62457. };
  62458. WindowsMotionController.prototype.dispose = function () {
  62459. _super.prototype.dispose.call(this);
  62460. this.onTrackpadChangedObservable.clear();
  62461. };
  62462. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  62463. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  62464. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  62465. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  62466. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  62467. return WindowsMotionController;
  62468. }(BABYLON.WebVRController));
  62469. BABYLON.WindowsMotionController = WindowsMotionController;
  62470. })(BABYLON || (BABYLON = {}));
  62471. //# sourceMappingURL=babylon.windowsMotionController.js.map
  62472. var BABYLON;
  62473. (function (BABYLON) {
  62474. var GearVRController = /** @class */ (function (_super) {
  62475. __extends(GearVRController, _super);
  62476. function GearVRController(vrGamepad) {
  62477. var _this = _super.call(this, vrGamepad) || this;
  62478. _this._buttonIndexToObservableNameMap = [
  62479. 'onTrackpadChangedObservable',
  62480. 'onTriggerStateChangedObservable' // Trigger
  62481. ];
  62482. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  62483. return _this;
  62484. }
  62485. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  62486. var _this = this;
  62487. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  62488. _this._defaultModel = newMeshes[1];
  62489. _this.attachToMesh(_this._defaultModel);
  62490. if (meshLoaded) {
  62491. meshLoaded(_this._defaultModel);
  62492. }
  62493. });
  62494. };
  62495. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  62496. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  62497. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  62498. // Only emit events for buttons that we know how to map from index to observable
  62499. var observable = this[observableName];
  62500. if (observable) {
  62501. observable.notifyObservers(state);
  62502. }
  62503. }
  62504. };
  62505. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  62506. GearVRController.MODEL_FILENAME = 'generic.babylon';
  62507. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  62508. return GearVRController;
  62509. }(BABYLON.WebVRController));
  62510. BABYLON.GearVRController = GearVRController;
  62511. })(BABYLON || (BABYLON = {}));
  62512. //# sourceMappingURL=babylon.gearVRController.js.map
  62513. var BABYLON;
  62514. (function (BABYLON) {
  62515. var FollowCamera = /** @class */ (function (_super) {
  62516. __extends(FollowCamera, _super);
  62517. function FollowCamera(name, position, scene, lockedTarget) {
  62518. if (lockedTarget === void 0) { lockedTarget = null; }
  62519. var _this = _super.call(this, name, position, scene) || this;
  62520. _this.radius = 12;
  62521. _this.rotationOffset = 0;
  62522. _this.heightOffset = 4;
  62523. _this.cameraAcceleration = 0.05;
  62524. _this.maxCameraSpeed = 20;
  62525. _this.lockedTarget = lockedTarget;
  62526. return _this;
  62527. }
  62528. FollowCamera.prototype.getRadians = function (degrees) {
  62529. return degrees * Math.PI / 180;
  62530. };
  62531. FollowCamera.prototype.follow = function (cameraTarget) {
  62532. if (!cameraTarget)
  62533. return;
  62534. var yRotation;
  62535. if (cameraTarget.rotationQuaternion) {
  62536. var rotMatrix = new BABYLON.Matrix();
  62537. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  62538. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  62539. }
  62540. else {
  62541. yRotation = cameraTarget.rotation.y;
  62542. }
  62543. var radians = this.getRadians(this.rotationOffset) + yRotation;
  62544. var targetPosition = cameraTarget.getAbsolutePosition();
  62545. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  62546. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  62547. var dx = targetX - this.position.x;
  62548. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  62549. var dz = (targetZ) - this.position.z;
  62550. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  62551. var vy = dy * this.cameraAcceleration;
  62552. var vz = dz * this.cameraAcceleration * 2;
  62553. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  62554. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62555. }
  62556. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  62557. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62558. }
  62559. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  62560. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62561. }
  62562. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  62563. this.setTarget(targetPosition);
  62564. };
  62565. FollowCamera.prototype._checkInputs = function () {
  62566. _super.prototype._checkInputs.call(this);
  62567. if (this.lockedTarget) {
  62568. this.follow(this.lockedTarget);
  62569. }
  62570. };
  62571. FollowCamera.prototype.getClassName = function () {
  62572. return "FollowCamera";
  62573. };
  62574. __decorate([
  62575. BABYLON.serialize()
  62576. ], FollowCamera.prototype, "radius", void 0);
  62577. __decorate([
  62578. BABYLON.serialize()
  62579. ], FollowCamera.prototype, "rotationOffset", void 0);
  62580. __decorate([
  62581. BABYLON.serialize()
  62582. ], FollowCamera.prototype, "heightOffset", void 0);
  62583. __decorate([
  62584. BABYLON.serialize()
  62585. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  62586. __decorate([
  62587. BABYLON.serialize()
  62588. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  62589. __decorate([
  62590. BABYLON.serializeAsMeshReference("lockedTargetId")
  62591. ], FollowCamera.prototype, "lockedTarget", void 0);
  62592. return FollowCamera;
  62593. }(BABYLON.TargetCamera));
  62594. BABYLON.FollowCamera = FollowCamera;
  62595. var ArcFollowCamera = /** @class */ (function (_super) {
  62596. __extends(ArcFollowCamera, _super);
  62597. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  62598. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  62599. _this.alpha = alpha;
  62600. _this.beta = beta;
  62601. _this.radius = radius;
  62602. _this.target = target;
  62603. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  62604. _this.follow();
  62605. return _this;
  62606. }
  62607. ArcFollowCamera.prototype.follow = function () {
  62608. if (!this.target) {
  62609. return;
  62610. }
  62611. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  62612. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  62613. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  62614. var targetPosition = this.target.getAbsolutePosition();
  62615. this.position = targetPosition.add(this._cartesianCoordinates);
  62616. this.setTarget(targetPosition);
  62617. };
  62618. ArcFollowCamera.prototype._checkInputs = function () {
  62619. _super.prototype._checkInputs.call(this);
  62620. this.follow();
  62621. };
  62622. ArcFollowCamera.prototype.getClassName = function () {
  62623. return "ArcFollowCamera";
  62624. };
  62625. return ArcFollowCamera;
  62626. }(BABYLON.TargetCamera));
  62627. BABYLON.ArcFollowCamera = ArcFollowCamera;
  62628. })(BABYLON || (BABYLON = {}));
  62629. //# sourceMappingURL=babylon.followCamera.js.map
  62630. var BABYLON;
  62631. (function (BABYLON) {
  62632. // We're mainly based on the logic defined into the FreeCamera code
  62633. var UniversalCamera = /** @class */ (function (_super) {
  62634. __extends(UniversalCamera, _super);
  62635. //-- end properties for backward compatibility for inputs
  62636. function UniversalCamera(name, position, scene) {
  62637. var _this = _super.call(this, name, position, scene) || this;
  62638. _this.inputs.addGamepad();
  62639. return _this;
  62640. }
  62641. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  62642. //-- Begin properties for backward compatibility for inputs
  62643. get: function () {
  62644. var gamepad = this.inputs.attached["gamepad"];
  62645. if (gamepad)
  62646. return gamepad.gamepadAngularSensibility;
  62647. return 0;
  62648. },
  62649. set: function (value) {
  62650. var gamepad = this.inputs.attached["gamepad"];
  62651. if (gamepad)
  62652. gamepad.gamepadAngularSensibility = value;
  62653. },
  62654. enumerable: true,
  62655. configurable: true
  62656. });
  62657. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  62658. get: function () {
  62659. var gamepad = this.inputs.attached["gamepad"];
  62660. if (gamepad)
  62661. return gamepad.gamepadMoveSensibility;
  62662. return 0;
  62663. },
  62664. set: function (value) {
  62665. var gamepad = this.inputs.attached["gamepad"];
  62666. if (gamepad)
  62667. gamepad.gamepadMoveSensibility = value;
  62668. },
  62669. enumerable: true,
  62670. configurable: true
  62671. });
  62672. UniversalCamera.prototype.getClassName = function () {
  62673. return "UniversalCamera";
  62674. };
  62675. return UniversalCamera;
  62676. }(BABYLON.TouchCamera));
  62677. BABYLON.UniversalCamera = UniversalCamera;
  62678. })(BABYLON || (BABYLON = {}));
  62679. //# sourceMappingURL=babylon.universalCamera.js.map
  62680. var BABYLON;
  62681. (function (BABYLON) {
  62682. // We're mainly based on the logic defined into the FreeCamera code
  62683. var GamepadCamera = /** @class */ (function (_super) {
  62684. __extends(GamepadCamera, _super);
  62685. //-- end properties for backward compatibility for inputs
  62686. function GamepadCamera(name, position, scene) {
  62687. return _super.call(this, name, position, scene) || this;
  62688. }
  62689. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  62690. //-- Begin properties for backward compatibility for inputs
  62691. get: function () {
  62692. var gamepad = this.inputs.attached["gamepad"];
  62693. if (gamepad)
  62694. return gamepad.gamepadAngularSensibility;
  62695. return 0;
  62696. },
  62697. set: function (value) {
  62698. var gamepad = this.inputs.attached["gamepad"];
  62699. if (gamepad)
  62700. gamepad.gamepadAngularSensibility = value;
  62701. },
  62702. enumerable: true,
  62703. configurable: true
  62704. });
  62705. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  62706. get: function () {
  62707. var gamepad = this.inputs.attached["gamepad"];
  62708. if (gamepad)
  62709. return gamepad.gamepadMoveSensibility;
  62710. return 0;
  62711. },
  62712. set: function (value) {
  62713. var gamepad = this.inputs.attached["gamepad"];
  62714. if (gamepad)
  62715. gamepad.gamepadMoveSensibility = value;
  62716. },
  62717. enumerable: true,
  62718. configurable: true
  62719. });
  62720. GamepadCamera.prototype.getClassName = function () {
  62721. return "GamepadCamera";
  62722. };
  62723. return GamepadCamera;
  62724. }(BABYLON.UniversalCamera));
  62725. BABYLON.GamepadCamera = GamepadCamera;
  62726. })(BABYLON || (BABYLON = {}));
  62727. //# sourceMappingURL=babylon.gamepadCamera.js.map
  62728. var BABYLON;
  62729. (function (BABYLON) {
  62730. var PostProcessRenderPipelineManager = /** @class */ (function () {
  62731. function PostProcessRenderPipelineManager() {
  62732. this._renderPipelines = {};
  62733. }
  62734. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  62735. this._renderPipelines[renderPipeline._name] = renderPipeline;
  62736. };
  62737. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  62738. if (unique === void 0) { unique = false; }
  62739. var renderPipeline = this._renderPipelines[renderPipelineName];
  62740. if (!renderPipeline) {
  62741. return;
  62742. }
  62743. renderPipeline._attachCameras(cameras, unique);
  62744. };
  62745. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  62746. var renderPipeline = this._renderPipelines[renderPipelineName];
  62747. if (!renderPipeline) {
  62748. return;
  62749. }
  62750. renderPipeline._detachCameras(cameras);
  62751. };
  62752. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62753. var renderPipeline = this._renderPipelines[renderPipelineName];
  62754. if (!renderPipeline) {
  62755. return;
  62756. }
  62757. renderPipeline._enableEffect(renderEffectName, cameras);
  62758. };
  62759. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62760. var renderPipeline = this._renderPipelines[renderPipelineName];
  62761. if (!renderPipeline) {
  62762. return;
  62763. }
  62764. renderPipeline._disableEffect(renderEffectName, cameras);
  62765. };
  62766. PostProcessRenderPipelineManager.prototype.update = function () {
  62767. for (var renderPipelineName in this._renderPipelines) {
  62768. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62769. var pipeline = this._renderPipelines[renderPipelineName];
  62770. if (!pipeline.isSupported) {
  62771. pipeline.dispose();
  62772. delete this._renderPipelines[renderPipelineName];
  62773. }
  62774. else {
  62775. pipeline._update();
  62776. }
  62777. }
  62778. }
  62779. };
  62780. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  62781. for (var renderPipelineName in this._renderPipelines) {
  62782. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62783. var pipeline = this._renderPipelines[renderPipelineName];
  62784. pipeline._rebuild();
  62785. }
  62786. }
  62787. };
  62788. PostProcessRenderPipelineManager.prototype.dispose = function () {
  62789. for (var renderPipelineName in this._renderPipelines) {
  62790. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62791. var pipeline = this._renderPipelines[renderPipelineName];
  62792. pipeline.dispose();
  62793. }
  62794. }
  62795. };
  62796. return PostProcessRenderPipelineManager;
  62797. }());
  62798. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  62799. })(BABYLON || (BABYLON = {}));
  62800. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  62801. var BABYLON;
  62802. (function (BABYLON) {
  62803. /**
  62804. * This represents a set of one or more post processes in Babylon.
  62805. * A post process can be used to apply a shader to a texture after it is rendered.
  62806. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  62807. */
  62808. var PostProcessRenderEffect = /** @class */ (function () {
  62809. /**
  62810. * Instantiates a post process render effect.
  62811. * A post process can be used to apply a shader to a texture after it is rendered.
  62812. * @param engine The engine the effect is tied to
  62813. * @param name The name of the effect
  62814. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  62815. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  62816. */
  62817. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  62818. this._name = name;
  62819. this._singleInstance = singleInstance || true;
  62820. this._getPostProcesses = getPostProcesses;
  62821. this._cameras = {};
  62822. this._indicesForCamera = {};
  62823. this._postProcesses = {};
  62824. }
  62825. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  62826. /**
  62827. * Checks if all the post processes in the effect are supported.
  62828. */
  62829. get: function () {
  62830. for (var index in this._postProcesses) {
  62831. for (var ppIndex in this._postProcesses[index]) {
  62832. if (!this._postProcesses[index][ppIndex].isSupported) {
  62833. return false;
  62834. }
  62835. }
  62836. }
  62837. return true;
  62838. },
  62839. enumerable: true,
  62840. configurable: true
  62841. });
  62842. /**
  62843. * Updates the current state of the effect
  62844. */
  62845. PostProcessRenderEffect.prototype._update = function () {
  62846. };
  62847. /**
  62848. * Attaches the effect on cameras
  62849. * @param cameras The camera to attach to.
  62850. */
  62851. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  62852. var _this = this;
  62853. var cameraKey;
  62854. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62855. if (!cams) {
  62856. return;
  62857. }
  62858. for (var i = 0; i < cams.length; i++) {
  62859. var camera = cams[i];
  62860. var cameraName = camera.name;
  62861. if (this._singleInstance) {
  62862. cameraKey = 0;
  62863. }
  62864. else {
  62865. cameraKey = cameraName;
  62866. }
  62867. if (!this._postProcesses[cameraKey]) {
  62868. var postProcess = this._getPostProcesses();
  62869. if (postProcess) {
  62870. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  62871. }
  62872. }
  62873. if (!this._indicesForCamera[cameraName]) {
  62874. this._indicesForCamera[cameraName] = [];
  62875. }
  62876. this._postProcesses[cameraKey].forEach(function (postProcess) {
  62877. var index = camera.attachPostProcess(postProcess);
  62878. _this._indicesForCamera[cameraName].push(index);
  62879. });
  62880. if (!this._cameras[cameraName]) {
  62881. this._cameras[cameraName] = camera;
  62882. }
  62883. }
  62884. };
  62885. /**
  62886. * Detatches the effect on cameras
  62887. * @param cameras The camera to detatch from.
  62888. */
  62889. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  62890. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62891. if (!cams) {
  62892. return;
  62893. }
  62894. for (var i = 0; i < cams.length; i++) {
  62895. var camera = cams[i];
  62896. var cameraName = camera.name;
  62897. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  62898. camera.detachPostProcess(postProcess);
  62899. });
  62900. if (this._cameras[cameraName]) {
  62901. //this._indicesForCamera.splice(index, 1);
  62902. this._cameras[cameraName] = null;
  62903. }
  62904. }
  62905. };
  62906. /**
  62907. * Enables the effect on given cameras
  62908. * @param cameras The camera to enable.
  62909. */
  62910. PostProcessRenderEffect.prototype._enable = function (cameras) {
  62911. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62912. if (!cams) {
  62913. return;
  62914. }
  62915. for (var i = 0; i < cams.length; i++) {
  62916. var camera = cams[i];
  62917. var cameraName = camera.name;
  62918. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  62919. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  62920. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  62921. }
  62922. }
  62923. }
  62924. };
  62925. /**
  62926. * Disables the effect on the given cameras
  62927. * @param cameras The camera to disable.
  62928. */
  62929. PostProcessRenderEffect.prototype._disable = function (cameras) {
  62930. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62931. if (!cams) {
  62932. return;
  62933. }
  62934. for (var i = 0; i < cams.length; i++) {
  62935. var camera = cams[i];
  62936. var cameraName = camera.Name;
  62937. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  62938. }
  62939. };
  62940. /**
  62941. * Gets a list of the post processes contained in the effect.
  62942. * @param camera The camera to get the post processes on.
  62943. * @returns The list of the post processes in the effect.
  62944. */
  62945. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  62946. if (this._singleInstance) {
  62947. return this._postProcesses[0];
  62948. }
  62949. else {
  62950. if (!camera) {
  62951. return null;
  62952. }
  62953. return this._postProcesses[camera.name];
  62954. }
  62955. };
  62956. return PostProcessRenderEffect;
  62957. }());
  62958. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  62959. })(BABYLON || (BABYLON = {}));
  62960. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  62961. var BABYLON;
  62962. (function (BABYLON) {
  62963. var PostProcessRenderPipeline = /** @class */ (function () {
  62964. function PostProcessRenderPipeline(engine, name) {
  62965. this._name = name;
  62966. this._renderEffects = {};
  62967. this._renderEffectsForIsolatedPass = new Array();
  62968. this._cameras = [];
  62969. }
  62970. PostProcessRenderPipeline.prototype.getClassName = function () {
  62971. return "PostProcessRenderPipeline";
  62972. };
  62973. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  62974. get: function () {
  62975. for (var renderEffectName in this._renderEffects) {
  62976. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62977. if (!this._renderEffects[renderEffectName].isSupported) {
  62978. return false;
  62979. }
  62980. }
  62981. }
  62982. return true;
  62983. },
  62984. enumerable: true,
  62985. configurable: true
  62986. });
  62987. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  62988. this._renderEffects[renderEffect._name] = renderEffect;
  62989. };
  62990. // private
  62991. PostProcessRenderPipeline.prototype._rebuild = function () {
  62992. };
  62993. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  62994. var renderEffects = this._renderEffects[renderEffectName];
  62995. if (!renderEffects) {
  62996. return;
  62997. }
  62998. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62999. };
  63000. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  63001. var renderEffects = this._renderEffects[renderEffectName];
  63002. if (!renderEffects) {
  63003. return;
  63004. }
  63005. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  63006. };
  63007. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  63008. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  63009. if (!cams) {
  63010. return;
  63011. }
  63012. var indicesToDelete = [];
  63013. var i;
  63014. for (i = 0; i < cams.length; i++) {
  63015. var camera = cams[i];
  63016. var cameraName = camera.name;
  63017. if (this._cameras.indexOf(camera) === -1) {
  63018. this._cameras[cameraName] = camera;
  63019. }
  63020. else if (unique) {
  63021. indicesToDelete.push(i);
  63022. }
  63023. }
  63024. for (i = 0; i < indicesToDelete.length; i++) {
  63025. cameras.splice(indicesToDelete[i], 1);
  63026. }
  63027. for (var renderEffectName in this._renderEffects) {
  63028. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  63029. this._renderEffects[renderEffectName]._attachCameras(cams);
  63030. }
  63031. }
  63032. };
  63033. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  63034. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  63035. if (!cams) {
  63036. return;
  63037. }
  63038. for (var renderEffectName in this._renderEffects) {
  63039. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  63040. this._renderEffects[renderEffectName]._detachCameras(cams);
  63041. }
  63042. }
  63043. for (var i = 0; i < cams.length; i++) {
  63044. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  63045. }
  63046. };
  63047. PostProcessRenderPipeline.prototype._update = function () {
  63048. for (var renderEffectName in this._renderEffects) {
  63049. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  63050. this._renderEffects[renderEffectName]._update();
  63051. }
  63052. }
  63053. for (var i = 0; i < this._cameras.length; i++) {
  63054. var cameraName = this._cameras[i].name;
  63055. if (this._renderEffectsForIsolatedPass[cameraName]) {
  63056. this._renderEffectsForIsolatedPass[cameraName]._update();
  63057. }
  63058. }
  63059. };
  63060. PostProcessRenderPipeline.prototype._reset = function () {
  63061. this._renderEffects = {};
  63062. this._renderEffectsForIsolatedPass = new Array();
  63063. };
  63064. PostProcessRenderPipeline.prototype.dispose = function () {
  63065. // Must be implemented by children
  63066. };
  63067. __decorate([
  63068. BABYLON.serialize()
  63069. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  63070. return PostProcessRenderPipeline;
  63071. }());
  63072. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  63073. })(BABYLON || (BABYLON = {}));
  63074. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  63075. var BABYLON;
  63076. (function (BABYLON) {
  63077. var DepthRenderer = /** @class */ (function () {
  63078. function DepthRenderer(scene, type) {
  63079. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  63080. var _this = this;
  63081. this._scene = scene;
  63082. var engine = scene.getEngine();
  63083. // Render target
  63084. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  63085. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63086. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63087. this._depthMap.refreshRate = 1;
  63088. this._depthMap.renderParticles = false;
  63089. this._depthMap.renderList = null;
  63090. // set default depth value to 1.0 (far away)
  63091. this._depthMap.onClearObservable.add(function (engine) {
  63092. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  63093. });
  63094. // Custom render function
  63095. var renderSubMesh = function (subMesh) {
  63096. var mesh = subMesh.getRenderingMesh();
  63097. var scene = _this._scene;
  63098. var engine = scene.getEngine();
  63099. var material = subMesh.getMaterial();
  63100. if (!material) {
  63101. return;
  63102. }
  63103. // Culling and reverse (right handed system)
  63104. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  63105. // Managing instances
  63106. var batch = mesh._getInstancesRenderList(subMesh._id);
  63107. if (batch.mustReturn) {
  63108. return;
  63109. }
  63110. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  63111. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  63112. engine.enableEffect(_this._effect);
  63113. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  63114. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  63115. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  63116. // Alpha test
  63117. if (material && material.needAlphaTesting()) {
  63118. var alphaTexture = material.getAlphaTestTexture();
  63119. if (alphaTexture) {
  63120. _this._effect.setTexture("diffuseSampler", alphaTexture);
  63121. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  63122. }
  63123. }
  63124. // Bones
  63125. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  63126. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  63127. }
  63128. // Draw
  63129. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  63130. }
  63131. };
  63132. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  63133. var index;
  63134. if (depthOnlySubMeshes.length) {
  63135. engine.setColorWrite(false);
  63136. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  63137. renderSubMesh(depthOnlySubMeshes.data[index]);
  63138. }
  63139. engine.setColorWrite(true);
  63140. }
  63141. for (index = 0; index < opaqueSubMeshes.length; index++) {
  63142. renderSubMesh(opaqueSubMeshes.data[index]);
  63143. }
  63144. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  63145. renderSubMesh(alphaTestSubMeshes.data[index]);
  63146. }
  63147. };
  63148. }
  63149. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  63150. var material = subMesh.getMaterial();
  63151. if (material.disableDepthWrite) {
  63152. return false;
  63153. }
  63154. var defines = [];
  63155. var attribs = [BABYLON.VertexBuffer.PositionKind];
  63156. var mesh = subMesh.getMesh();
  63157. // Alpha test
  63158. if (material && material.needAlphaTesting()) {
  63159. defines.push("#define ALPHATEST");
  63160. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63161. attribs.push(BABYLON.VertexBuffer.UVKind);
  63162. defines.push("#define UV1");
  63163. }
  63164. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  63165. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63166. defines.push("#define UV2");
  63167. }
  63168. }
  63169. // Bones
  63170. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63171. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63172. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63173. if (mesh.numBoneInfluencers > 4) {
  63174. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63175. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63176. }
  63177. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63178. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  63179. }
  63180. else {
  63181. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63182. }
  63183. // Instances
  63184. if (useInstances) {
  63185. defines.push("#define INSTANCES");
  63186. attribs.push("world0");
  63187. attribs.push("world1");
  63188. attribs.push("world2");
  63189. attribs.push("world3");
  63190. }
  63191. // Get correct effect
  63192. var join = defines.join("\n");
  63193. if (this._cachedDefines !== join) {
  63194. this._cachedDefines = join;
  63195. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  63196. }
  63197. return this._effect.isReady();
  63198. };
  63199. DepthRenderer.prototype.getDepthMap = function () {
  63200. return this._depthMap;
  63201. };
  63202. // Methods
  63203. DepthRenderer.prototype.dispose = function () {
  63204. this._depthMap.dispose();
  63205. };
  63206. return DepthRenderer;
  63207. }());
  63208. BABYLON.DepthRenderer = DepthRenderer;
  63209. })(BABYLON || (BABYLON = {}));
  63210. //# sourceMappingURL=babylon.depthRenderer.js.map
  63211. var BABYLON;
  63212. (function (BABYLON) {
  63213. var SSAORenderingPipeline = /** @class */ (function (_super) {
  63214. __extends(SSAORenderingPipeline, _super);
  63215. /**
  63216. * @constructor
  63217. * @param {string} name - The rendering pipeline name
  63218. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63219. * @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 }
  63220. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63221. */
  63222. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  63223. var _this = _super.call(this, scene.getEngine(), name) || this;
  63224. // Members
  63225. /**
  63226. * The PassPostProcess id in the pipeline that contains the original scene color
  63227. * @type {string}
  63228. */
  63229. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  63230. /**
  63231. * The SSAO PostProcess id in the pipeline
  63232. * @type {string}
  63233. */
  63234. _this.SSAORenderEffect = "SSAORenderEffect";
  63235. /**
  63236. * The horizontal blur PostProcess id in the pipeline
  63237. * @type {string}
  63238. */
  63239. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  63240. /**
  63241. * The vertical blur PostProcess id in the pipeline
  63242. * @type {string}
  63243. */
  63244. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  63245. /**
  63246. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  63247. * @type {string}
  63248. */
  63249. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  63250. /**
  63251. * The output strength of the SSAO post-process. Default value is 1.0.
  63252. * @type {number}
  63253. */
  63254. _this.totalStrength = 1.0;
  63255. /**
  63256. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  63257. * @type {number}
  63258. */
  63259. _this.radius = 0.0001;
  63260. /**
  63261. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  63262. * Must not be equal to fallOff and superior to fallOff.
  63263. * Default value is 0.975
  63264. * @type {number}
  63265. */
  63266. _this.area = 0.0075;
  63267. /**
  63268. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  63269. * Must not be equal to area and inferior to area.
  63270. * Default value is 0.0
  63271. * @type {number}
  63272. */
  63273. _this.fallOff = 0.000001;
  63274. /**
  63275. * The base color of the SSAO post-process
  63276. * The final result is "base + ssao" between [0, 1]
  63277. * @type {number}
  63278. */
  63279. _this.base = 0.5;
  63280. _this._firstUpdate = true;
  63281. _this._scene = scene;
  63282. // Set up assets
  63283. _this._createRandomTexture();
  63284. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  63285. var ssaoRatio = ratio.ssaoRatio || ratio;
  63286. var combineRatio = ratio.combineRatio || ratio;
  63287. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  63288. _this._createSSAOPostProcess(ssaoRatio);
  63289. _this._createBlurPostProcess(ssaoRatio);
  63290. _this._createSSAOCombinePostProcess(combineRatio);
  63291. // Set up pipeline
  63292. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  63293. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  63294. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  63295. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  63296. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  63297. // Finish
  63298. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63299. if (cameras)
  63300. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63301. return _this;
  63302. }
  63303. // Public Methods
  63304. /**
  63305. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  63306. */
  63307. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  63308. if (disableDepthRender === void 0) { disableDepthRender = false; }
  63309. for (var i = 0; i < this._scene.cameras.length; i++) {
  63310. var camera = this._scene.cameras[i];
  63311. this._originalColorPostProcess.dispose(camera);
  63312. this._ssaoPostProcess.dispose(camera);
  63313. this._blurHPostProcess.dispose(camera);
  63314. this._blurVPostProcess.dispose(camera);
  63315. this._ssaoCombinePostProcess.dispose(camera);
  63316. }
  63317. this._randomTexture.dispose();
  63318. if (disableDepthRender)
  63319. this._scene.disableDepthRenderer();
  63320. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63321. _super.prototype.dispose.call(this);
  63322. };
  63323. // Private Methods
  63324. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  63325. var _this = this;
  63326. var size = 16;
  63327. 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);
  63328. 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);
  63329. this._blurHPostProcess.onActivateObservable.add(function () {
  63330. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  63331. _this._blurHPostProcess.kernel = size * dw;
  63332. });
  63333. this._blurVPostProcess.onActivateObservable.add(function () {
  63334. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  63335. _this._blurVPostProcess.kernel = size * dw;
  63336. });
  63337. };
  63338. SSAORenderingPipeline.prototype._rebuild = function () {
  63339. this._firstUpdate = true;
  63340. _super.prototype._rebuild.call(this);
  63341. };
  63342. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  63343. var _this = this;
  63344. var numSamples = 16;
  63345. var sampleSphere = [
  63346. 0.5381, 0.1856, -0.4319,
  63347. 0.1379, 0.2486, 0.4430,
  63348. 0.3371, 0.5679, -0.0057,
  63349. -0.6999, -0.0451, -0.0019,
  63350. 0.0689, -0.1598, -0.8547,
  63351. 0.0560, 0.0069, -0.1843,
  63352. -0.0146, 0.1402, 0.0762,
  63353. 0.0100, -0.1924, -0.0344,
  63354. -0.3577, -0.5301, -0.4358,
  63355. -0.3169, 0.1063, 0.0158,
  63356. 0.0103, -0.5869, 0.0046,
  63357. -0.0897, -0.4940, 0.3287,
  63358. 0.7119, -0.0154, -0.0918,
  63359. -0.0533, 0.0596, -0.5411,
  63360. 0.0352, -0.0631, 0.5460,
  63361. -0.4776, 0.2847, -0.0271
  63362. ];
  63363. var samplesFactor = 1.0 / numSamples;
  63364. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  63365. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  63366. "area", "fallOff", "base", "range", "viewport"
  63367. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  63368. this._ssaoPostProcess.onApply = function (effect) {
  63369. if (_this._firstUpdate) {
  63370. effect.setArray3("sampleSphere", sampleSphere);
  63371. effect.setFloat("samplesFactor", samplesFactor);
  63372. effect.setFloat("randTextureTiles", 4.0);
  63373. }
  63374. effect.setFloat("totalStrength", _this.totalStrength);
  63375. effect.setFloat("radius", _this.radius);
  63376. effect.setFloat("area", _this.area);
  63377. effect.setFloat("fallOff", _this.fallOff);
  63378. effect.setFloat("base", _this.base);
  63379. effect.setTexture("textureSampler", _this._depthTexture);
  63380. effect.setTexture("randomSampler", _this._randomTexture);
  63381. };
  63382. };
  63383. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  63384. var _this = this;
  63385. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63386. this._ssaoCombinePostProcess.onApply = function (effect) {
  63387. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  63388. };
  63389. };
  63390. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  63391. var size = 512;
  63392. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  63393. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63394. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63395. var context = this._randomTexture.getContext();
  63396. var rand = function (min, max) {
  63397. return Math.random() * (max - min) + min;
  63398. };
  63399. var randVector = BABYLON.Vector3.Zero();
  63400. for (var x = 0; x < size; x++) {
  63401. for (var y = 0; y < size; y++) {
  63402. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  63403. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  63404. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  63405. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  63406. context.fillRect(x, y, 1, 1);
  63407. }
  63408. }
  63409. this._randomTexture.update(false);
  63410. };
  63411. __decorate([
  63412. BABYLON.serialize()
  63413. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  63414. __decorate([
  63415. BABYLON.serialize()
  63416. ], SSAORenderingPipeline.prototype, "radius", void 0);
  63417. __decorate([
  63418. BABYLON.serialize()
  63419. ], SSAORenderingPipeline.prototype, "area", void 0);
  63420. __decorate([
  63421. BABYLON.serialize()
  63422. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  63423. __decorate([
  63424. BABYLON.serialize()
  63425. ], SSAORenderingPipeline.prototype, "base", void 0);
  63426. return SSAORenderingPipeline;
  63427. }(BABYLON.PostProcessRenderPipeline));
  63428. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  63429. })(BABYLON || (BABYLON = {}));
  63430. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  63431. var BABYLON;
  63432. (function (BABYLON) {
  63433. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  63434. __extends(SSAO2RenderingPipeline, _super);
  63435. /**
  63436. * @constructor
  63437. * @param {string} name - The rendering pipeline name
  63438. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63439. * @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 }
  63440. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63441. */
  63442. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  63443. var _this = _super.call(this, scene.getEngine(), name) || this;
  63444. // Members
  63445. /**
  63446. * The PassPostProcess id in the pipeline that contains the original scene color
  63447. * @type {string}
  63448. */
  63449. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  63450. /**
  63451. * The SSAO PostProcess id in the pipeline
  63452. * @type {string}
  63453. */
  63454. _this.SSAORenderEffect = "SSAORenderEffect";
  63455. /**
  63456. * The horizontal blur PostProcess id in the pipeline
  63457. * @type {string}
  63458. */
  63459. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  63460. /**
  63461. * The vertical blur PostProcess id in the pipeline
  63462. * @type {string}
  63463. */
  63464. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  63465. /**
  63466. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  63467. * @type {string}
  63468. */
  63469. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  63470. /**
  63471. * The output strength of the SSAO post-process. Default value is 1.0.
  63472. * @type {number}
  63473. */
  63474. _this.totalStrength = 1.0;
  63475. /**
  63476. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  63477. * @type {number}
  63478. */
  63479. _this.maxZ = 100.0;
  63480. /**
  63481. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  63482. * @type {number}
  63483. */
  63484. _this.minZAspect = 0.2;
  63485. /**
  63486. * Number of samples used for the SSAO calculations. Default value is 8
  63487. * @type {number}
  63488. */
  63489. _this._samples = 8;
  63490. /**
  63491. * Are we using bilateral blur ?
  63492. * @type {boolean}
  63493. */
  63494. _this._expensiveBlur = true;
  63495. /**
  63496. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  63497. * @type {number}
  63498. */
  63499. _this.radius = 2.0;
  63500. /**
  63501. * The base color of the SSAO post-process
  63502. * The final result is "base + ssao" between [0, 1]
  63503. * @type {number}
  63504. */
  63505. _this.base = 0.1;
  63506. _this._firstUpdate = true;
  63507. _this._scene = scene;
  63508. if (!_this.isSupported) {
  63509. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  63510. return _this;
  63511. }
  63512. var ssaoRatio = ratio.ssaoRatio || ratio;
  63513. var blurRatio = ratio.blurRatio || ratio;
  63514. // Set up assets
  63515. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  63516. _this._createRandomTexture();
  63517. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  63518. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  63519. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  63520. _this._createSSAOPostProcess(1.0);
  63521. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  63522. _this._createSSAOCombinePostProcess(blurRatio);
  63523. // Set up pipeline
  63524. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  63525. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  63526. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  63527. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  63528. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  63529. // Finish
  63530. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63531. if (cameras)
  63532. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63533. return _this;
  63534. }
  63535. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  63536. get: function () {
  63537. return this._samples;
  63538. },
  63539. set: function (n) {
  63540. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  63541. this._samples = n;
  63542. this._sampleSphere = this._generateHemisphere();
  63543. this._firstUpdate = true;
  63544. },
  63545. enumerable: true,
  63546. configurable: true
  63547. });
  63548. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  63549. get: function () {
  63550. return this._expensiveBlur;
  63551. },
  63552. set: function (b) {
  63553. 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"]);
  63554. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  63555. this._expensiveBlur = b;
  63556. this._firstUpdate = true;
  63557. },
  63558. enumerable: true,
  63559. configurable: true
  63560. });
  63561. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  63562. /**
  63563. * Support test.
  63564. * @type {boolean}
  63565. */
  63566. get: function () {
  63567. var engine = BABYLON.Engine.LastCreatedEngine;
  63568. if (!engine) {
  63569. return false;
  63570. }
  63571. return engine.getCaps().drawBuffersExtension;
  63572. },
  63573. enumerable: true,
  63574. configurable: true
  63575. });
  63576. // Public Methods
  63577. /**
  63578. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  63579. */
  63580. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  63581. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  63582. for (var i = 0; i < this._scene.cameras.length; i++) {
  63583. var camera = this._scene.cameras[i];
  63584. this._originalColorPostProcess.dispose(camera);
  63585. this._ssaoPostProcess.dispose(camera);
  63586. this._blurHPostProcess.dispose(camera);
  63587. this._blurVPostProcess.dispose(camera);
  63588. this._ssaoCombinePostProcess.dispose(camera);
  63589. }
  63590. this._randomTexture.dispose();
  63591. if (disableGeometryBufferRenderer)
  63592. this._scene.disableGeometryBufferRenderer();
  63593. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63594. _super.prototype.dispose.call(this);
  63595. };
  63596. // Private Methods
  63597. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  63598. var _this = this;
  63599. this._samplerOffsets = [];
  63600. var expensive = this.expensiveBlur;
  63601. for (var i = -8; i < 8; i++) {
  63602. this._samplerOffsets.push(i * 2 + 0.5);
  63603. }
  63604. 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");
  63605. this._blurHPostProcess.onApply = function (effect) {
  63606. if (!_this._scene.activeCamera) {
  63607. return;
  63608. }
  63609. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  63610. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63611. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63612. effect.setFloat("radius", _this.radius);
  63613. effect.setTexture("depthSampler", _this._depthTexture);
  63614. if (_this._firstUpdate) {
  63615. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63616. }
  63617. };
  63618. 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");
  63619. this._blurVPostProcess.onApply = function (effect) {
  63620. if (!_this._scene.activeCamera) {
  63621. return;
  63622. }
  63623. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  63624. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63625. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63626. effect.setFloat("radius", _this.radius);
  63627. effect.setTexture("depthSampler", _this._depthTexture);
  63628. if (_this._firstUpdate) {
  63629. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63630. _this._firstUpdate = false;
  63631. }
  63632. };
  63633. };
  63634. SSAO2RenderingPipeline.prototype._rebuild = function () {
  63635. this._firstUpdate = true;
  63636. _super.prototype._rebuild.call(this);
  63637. };
  63638. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  63639. var numSamples = this.samples;
  63640. var result = [];
  63641. var vector, scale;
  63642. var rand = function (min, max) {
  63643. return Math.random() * (max - min) + min;
  63644. };
  63645. var i = 0;
  63646. while (i < numSamples) {
  63647. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  63648. vector.normalize();
  63649. scale = i / numSamples;
  63650. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  63651. vector.scaleInPlace(scale);
  63652. result.push(vector.x, vector.y, vector.z);
  63653. i++;
  63654. }
  63655. return result;
  63656. };
  63657. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  63658. var _this = this;
  63659. var numSamples = this.samples;
  63660. this._sampleSphere = this._generateHemisphere();
  63661. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  63662. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  63663. "base", "range", "projection", "near", "far", "texelSize",
  63664. "xViewport", "yViewport", "maxZ", "minZAspect"
  63665. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  63666. this._ssaoPostProcess.onApply = function (effect) {
  63667. if (_this._firstUpdate) {
  63668. effect.setArray3("sampleSphere", _this._sampleSphere);
  63669. effect.setFloat("randTextureTiles", 4.0);
  63670. }
  63671. if (!_this._scene.activeCamera) {
  63672. return;
  63673. }
  63674. effect.setFloat("samplesFactor", 1 / _this.samples);
  63675. effect.setFloat("totalStrength", _this.totalStrength);
  63676. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  63677. effect.setFloat("radius", _this.radius);
  63678. effect.setFloat("maxZ", _this.maxZ);
  63679. effect.setFloat("minZAspect", _this.minZAspect);
  63680. effect.setFloat("base", _this.base);
  63681. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63682. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63683. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  63684. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  63685. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  63686. effect.setTexture("textureSampler", _this._depthTexture);
  63687. effect.setTexture("normalSampler", _this._normalTexture);
  63688. effect.setTexture("randomSampler", _this._randomTexture);
  63689. };
  63690. };
  63691. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  63692. var _this = this;
  63693. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63694. this._ssaoCombinePostProcess.onApply = function (effect) {
  63695. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  63696. };
  63697. };
  63698. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  63699. var size = 512;
  63700. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  63701. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63702. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63703. var context = this._randomTexture.getContext();
  63704. var rand = function (min, max) {
  63705. return Math.random() * (max - min) + min;
  63706. };
  63707. var randVector = BABYLON.Vector3.Zero();
  63708. for (var x = 0; x < size; x++) {
  63709. for (var y = 0; y < size; y++) {
  63710. randVector.x = rand(0.0, 1.0);
  63711. randVector.y = rand(0.0, 1.0);
  63712. randVector.z = 0.0;
  63713. randVector.normalize();
  63714. randVector.scaleInPlace(255);
  63715. randVector.x = Math.floor(randVector.x);
  63716. randVector.y = Math.floor(randVector.y);
  63717. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  63718. context.fillRect(x, y, 1, 1);
  63719. }
  63720. }
  63721. this._randomTexture.update(false);
  63722. };
  63723. __decorate([
  63724. BABYLON.serialize()
  63725. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  63726. __decorate([
  63727. BABYLON.serialize()
  63728. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  63729. __decorate([
  63730. BABYLON.serialize()
  63731. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  63732. __decorate([
  63733. BABYLON.serialize("samples")
  63734. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  63735. __decorate([
  63736. BABYLON.serialize("expensiveBlur")
  63737. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  63738. __decorate([
  63739. BABYLON.serialize()
  63740. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  63741. __decorate([
  63742. BABYLON.serialize()
  63743. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  63744. return SSAO2RenderingPipeline;
  63745. }(BABYLON.PostProcessRenderPipeline));
  63746. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  63747. })(BABYLON || (BABYLON = {}));
  63748. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  63749. // BABYLON.JS Chromatic Aberration GLSL Shader
  63750. // Author: Olivier Guyot
  63751. // Separates very slightly R, G and B colors on the edges of the screen
  63752. // Inspired by Francois Tarlier & Martins Upitis
  63753. var BABYLON;
  63754. (function (BABYLON) {
  63755. var LensRenderingPipeline = /** @class */ (function (_super) {
  63756. __extends(LensRenderingPipeline, _super);
  63757. /**
  63758. * @constructor
  63759. *
  63760. * Effect parameters are as follow:
  63761. * {
  63762. * chromatic_aberration: number; // from 0 to x (1 for realism)
  63763. * edge_blur: number; // from 0 to x (1 for realism)
  63764. * distortion: number; // from 0 to x (1 for realism)
  63765. * grain_amount: number; // from 0 to 1
  63766. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  63767. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  63768. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  63769. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  63770. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  63771. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  63772. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  63773. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  63774. * }
  63775. * Note: if an effect parameter is unset, effect is disabled
  63776. *
  63777. * @param {string} name - The rendering pipeline name
  63778. * @param {object} parameters - An object containing all parameters (see above)
  63779. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63780. * @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)
  63781. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63782. */
  63783. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  63784. if (ratio === void 0) { ratio = 1.0; }
  63785. var _this = _super.call(this, scene.getEngine(), name) || this;
  63786. // Lens effects can be of the following:
  63787. // - chromatic aberration (slight shift of RGB colors)
  63788. // - blur on the edge of the lens
  63789. // - lens distortion
  63790. // - depth-of-field blur & highlights enhancing
  63791. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  63792. // - grain effect (noise or custom texture)
  63793. // Two additional texture samplers are needed:
  63794. // - depth map (for depth-of-field)
  63795. // - grain texture
  63796. /**
  63797. * The chromatic aberration PostProcess id in the pipeline
  63798. * @type {string}
  63799. */
  63800. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  63801. /**
  63802. * The highlights enhancing PostProcess id in the pipeline
  63803. * @type {string}
  63804. */
  63805. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  63806. /**
  63807. * The depth-of-field PostProcess id in the pipeline
  63808. * @type {string}
  63809. */
  63810. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  63811. _this._scene = scene;
  63812. // Fetch texture samplers
  63813. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  63814. if (parameters.grain_texture) {
  63815. _this._grainTexture = parameters.grain_texture;
  63816. }
  63817. else {
  63818. _this._createGrainTexture();
  63819. }
  63820. // save parameters
  63821. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  63822. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  63823. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  63824. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  63825. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  63826. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  63827. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  63828. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  63829. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  63830. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  63831. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  63832. // Create effects
  63833. _this._createChromaticAberrationPostProcess(ratio);
  63834. _this._createHighlightsPostProcess(ratio);
  63835. _this._createDepthOfFieldPostProcess(ratio / 4);
  63836. // Set up pipeline
  63837. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  63838. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  63839. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  63840. if (_this._highlightsGain === -1) {
  63841. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  63842. }
  63843. // Finish
  63844. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63845. if (cameras) {
  63846. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63847. }
  63848. return _this;
  63849. }
  63850. // public methods (self explanatory)
  63851. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  63852. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  63853. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  63854. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  63855. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  63856. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  63857. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  63858. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  63859. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  63860. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  63861. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  63862. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  63863. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  63864. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  63865. };
  63866. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  63867. this._highlightsPostProcess.updateEffect();
  63868. };
  63869. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  63870. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  63871. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  63872. this._highlightsGain = amount;
  63873. };
  63874. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  63875. if (this._highlightsGain === -1) {
  63876. this._highlightsGain = 1.0;
  63877. }
  63878. this._highlightsThreshold = amount;
  63879. };
  63880. LensRenderingPipeline.prototype.disableHighlights = function () {
  63881. this._highlightsGain = -1;
  63882. };
  63883. /**
  63884. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  63885. */
  63886. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  63887. if (disableDepthRender === void 0) { disableDepthRender = false; }
  63888. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63889. this._chromaticAberrationPostProcess = null;
  63890. this._highlightsPostProcess = null;
  63891. this._depthOfFieldPostProcess = null;
  63892. this._grainTexture.dispose();
  63893. if (disableDepthRender)
  63894. this._scene.disableDepthRenderer();
  63895. };
  63896. // colors shifting and distortion
  63897. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  63898. var _this = this;
  63899. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  63900. [], // samplers
  63901. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63902. this._chromaticAberrationPostProcess.onApply = function (effect) {
  63903. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  63904. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63905. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63906. };
  63907. };
  63908. // highlights enhancing
  63909. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  63910. var _this = this;
  63911. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  63912. [], // samplers
  63913. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  63914. this._highlightsPostProcess.onApply = function (effect) {
  63915. effect.setFloat('gain', _this._highlightsGain);
  63916. effect.setFloat('threshold', _this._highlightsThreshold);
  63917. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  63918. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63919. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63920. };
  63921. };
  63922. // colors shifting and distortion
  63923. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  63924. var _this = this;
  63925. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  63926. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  63927. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  63928. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63929. this._depthOfFieldPostProcess.onApply = function (effect) {
  63930. effect.setTexture("depthSampler", _this._depthTexture);
  63931. effect.setTexture("grainSampler", _this._grainTexture);
  63932. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  63933. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  63934. effect.setFloat('grain_amount', _this._grainAmount);
  63935. effect.setBool('blur_noise', _this._blurNoise);
  63936. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63937. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63938. effect.setFloat('distortion', _this._distortion);
  63939. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  63940. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  63941. effect.setFloat('aperture', _this._dofAperture);
  63942. effect.setFloat('darken', _this._dofDarken);
  63943. effect.setFloat('edge_blur', _this._edgeBlur);
  63944. effect.setBool('highlights', (_this._highlightsGain !== -1));
  63945. if (_this._scene.activeCamera) {
  63946. effect.setFloat('near', _this._scene.activeCamera.minZ);
  63947. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  63948. }
  63949. };
  63950. };
  63951. // creates a black and white random noise texture, 512x512
  63952. LensRenderingPipeline.prototype._createGrainTexture = function () {
  63953. var size = 512;
  63954. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63955. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63956. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63957. var context = this._grainTexture.getContext();
  63958. var rand = function (min, max) {
  63959. return Math.random() * (max - min) + min;
  63960. };
  63961. var value;
  63962. for (var x = 0; x < size; x++) {
  63963. for (var y = 0; y < size; y++) {
  63964. value = Math.floor(rand(0.42, 0.58) * 255);
  63965. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  63966. context.fillRect(x, y, 1, 1);
  63967. }
  63968. }
  63969. this._grainTexture.update(false);
  63970. };
  63971. return LensRenderingPipeline;
  63972. }(BABYLON.PostProcessRenderPipeline));
  63973. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  63974. })(BABYLON || (BABYLON = {}));
  63975. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  63976. var BABYLON;
  63977. (function (BABYLON) {
  63978. var StandardRenderingPipeline = /** @class */ (function (_super) {
  63979. __extends(StandardRenderingPipeline, _super);
  63980. /**
  63981. * @constructor
  63982. * @param {string} name - The rendering pipeline name
  63983. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63984. * @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)
  63985. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  63986. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63987. */
  63988. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  63989. if (originalPostProcess === void 0) { originalPostProcess = null; }
  63990. var _this = _super.call(this, scene.getEngine(), name) || this;
  63991. _this.downSampleX4PostProcess = null;
  63992. _this.brightPassPostProcess = null;
  63993. _this.blurHPostProcesses = [];
  63994. _this.blurVPostProcesses = [];
  63995. _this.textureAdderPostProcess = null;
  63996. _this.volumetricLightPostProcess = null;
  63997. _this.volumetricLightSmoothXPostProcess = null;
  63998. _this.volumetricLightSmoothYPostProcess = null;
  63999. _this.volumetricLightMergePostProces = null;
  64000. _this.volumetricLightFinalPostProcess = null;
  64001. _this.luminancePostProcess = null;
  64002. _this.luminanceDownSamplePostProcesses = [];
  64003. _this.hdrPostProcess = null;
  64004. _this.textureAdderFinalPostProcess = null;
  64005. _this.lensFlareFinalPostProcess = null;
  64006. _this.hdrFinalPostProcess = null;
  64007. _this.lensFlarePostProcess = null;
  64008. _this.lensFlareComposePostProcess = null;
  64009. _this.motionBlurPostProcess = null;
  64010. _this.depthOfFieldPostProcess = null;
  64011. // Values
  64012. _this.brightThreshold = 1.0;
  64013. _this.blurWidth = 512.0;
  64014. _this.horizontalBlur = false;
  64015. _this.exposure = 1.0;
  64016. _this.lensTexture = null;
  64017. _this.volumetricLightCoefficient = 0.2;
  64018. _this.volumetricLightPower = 4.0;
  64019. _this.volumetricLightBlurScale = 64.0;
  64020. _this.sourceLight = null;
  64021. _this.hdrMinimumLuminance = 1.0;
  64022. _this.hdrDecreaseRate = 0.5;
  64023. _this.hdrIncreaseRate = 0.5;
  64024. _this.lensColorTexture = null;
  64025. _this.lensFlareStrength = 20.0;
  64026. _this.lensFlareGhostDispersal = 1.4;
  64027. _this.lensFlareHaloWidth = 0.7;
  64028. _this.lensFlareDistortionStrength = 16.0;
  64029. _this.lensStarTexture = null;
  64030. _this.lensFlareDirtTexture = null;
  64031. _this.depthOfFieldDistance = 10.0;
  64032. _this.depthOfFieldBlurWidth = 64.0;
  64033. _this.motionStrength = 1.0;
  64034. // IAnimatable
  64035. _this.animations = [];
  64036. _this._currentDepthOfFieldSource = null;
  64037. _this._hdrCurrentLuminance = 1.0;
  64038. // Getters and setters
  64039. _this._bloomEnabled = true;
  64040. _this._depthOfFieldEnabled = false;
  64041. _this._vlsEnabled = false;
  64042. _this._lensFlareEnabled = false;
  64043. _this._hdrEnabled = false;
  64044. _this._motionBlurEnabled = false;
  64045. _this._motionBlurSamples = 64.0;
  64046. _this._volumetricLightStepsCount = 50.0;
  64047. _this._cameras = cameras || [];
  64048. // Initialize
  64049. _this._scene = scene;
  64050. _this._basePostProcess = originalPostProcess;
  64051. _this._ratio = ratio;
  64052. // Misc
  64053. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64054. // Finish
  64055. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64056. _this._buildPipeline();
  64057. return _this;
  64058. }
  64059. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  64060. get: function () {
  64061. return this._bloomEnabled;
  64062. },
  64063. set: function (enabled) {
  64064. if (this._bloomEnabled === enabled) {
  64065. return;
  64066. }
  64067. this._bloomEnabled = enabled;
  64068. this._buildPipeline();
  64069. },
  64070. enumerable: true,
  64071. configurable: true
  64072. });
  64073. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  64074. get: function () {
  64075. return this._depthOfFieldEnabled;
  64076. },
  64077. set: function (enabled) {
  64078. if (this._depthOfFieldEnabled === enabled) {
  64079. return;
  64080. }
  64081. this._depthOfFieldEnabled = enabled;
  64082. this._buildPipeline();
  64083. },
  64084. enumerable: true,
  64085. configurable: true
  64086. });
  64087. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  64088. get: function () {
  64089. return this._lensFlareEnabled;
  64090. },
  64091. set: function (enabled) {
  64092. if (this._lensFlareEnabled === enabled) {
  64093. return;
  64094. }
  64095. this._lensFlareEnabled = enabled;
  64096. this._buildPipeline();
  64097. },
  64098. enumerable: true,
  64099. configurable: true
  64100. });
  64101. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  64102. get: function () {
  64103. return this._hdrEnabled;
  64104. },
  64105. set: function (enabled) {
  64106. if (this._hdrEnabled === enabled) {
  64107. return;
  64108. }
  64109. this._hdrEnabled = enabled;
  64110. this._buildPipeline();
  64111. },
  64112. enumerable: true,
  64113. configurable: true
  64114. });
  64115. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  64116. get: function () {
  64117. return this._vlsEnabled;
  64118. },
  64119. set: function (enabled) {
  64120. if (this._vlsEnabled === enabled) {
  64121. return;
  64122. }
  64123. if (enabled) {
  64124. var geometry = this._scene.enableGeometryBufferRenderer();
  64125. if (!geometry) {
  64126. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  64127. return;
  64128. }
  64129. }
  64130. this._vlsEnabled = enabled;
  64131. this._buildPipeline();
  64132. },
  64133. enumerable: true,
  64134. configurable: true
  64135. });
  64136. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  64137. get: function () {
  64138. return this._motionBlurEnabled;
  64139. },
  64140. set: function (enabled) {
  64141. if (this._motionBlurEnabled === enabled) {
  64142. return;
  64143. }
  64144. this._motionBlurEnabled = enabled;
  64145. this._buildPipeline();
  64146. },
  64147. enumerable: true,
  64148. configurable: true
  64149. });
  64150. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  64151. get: function () {
  64152. return this._volumetricLightStepsCount;
  64153. },
  64154. set: function (count) {
  64155. if (this.volumetricLightPostProcess) {
  64156. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  64157. }
  64158. this._volumetricLightStepsCount = count;
  64159. },
  64160. enumerable: true,
  64161. configurable: true
  64162. });
  64163. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  64164. get: function () {
  64165. return this._motionBlurSamples;
  64166. },
  64167. set: function (samples) {
  64168. if (this.motionBlurPostProcess) {
  64169. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  64170. }
  64171. this._motionBlurSamples = samples;
  64172. },
  64173. enumerable: true,
  64174. configurable: true
  64175. });
  64176. StandardRenderingPipeline.prototype._buildPipeline = function () {
  64177. var _this = this;
  64178. var ratio = this._ratio;
  64179. var scene = this._scene;
  64180. this._disposePostProcesses();
  64181. this._reset();
  64182. // Create pass post-process
  64183. if (!this._basePostProcess) {
  64184. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  64185. this.originalPostProcess.onApply = function (effect) {
  64186. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  64187. };
  64188. }
  64189. else {
  64190. this.originalPostProcess = this._basePostProcess;
  64191. }
  64192. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  64193. this._currentDepthOfFieldSource = this.originalPostProcess;
  64194. if (this._vlsEnabled) {
  64195. // Create volumetric light
  64196. this._createVolumetricLightPostProcess(scene, ratio);
  64197. // Create volumetric light final post-process
  64198. 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);
  64199. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  64200. }
  64201. if (this._bloomEnabled) {
  64202. // Create down sample X4 post-process
  64203. this._createDownSampleX4PostProcess(scene, ratio / 2);
  64204. // Create bright pass post-process
  64205. this._createBrightPassPostProcess(scene, ratio / 2);
  64206. // Create gaussian blur post-processes (down sampling blurs)
  64207. this._createBlurPostProcesses(scene, ratio / 4, 1);
  64208. // Create texture adder post-process
  64209. this._createTextureAdderPostProcess(scene, ratio);
  64210. // Create depth-of-field source post-process
  64211. 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);
  64212. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  64213. }
  64214. if (this._lensFlareEnabled) {
  64215. // Create lens flare post-process
  64216. this._createLensFlarePostProcess(scene, ratio);
  64217. // Create depth-of-field source post-process post lens-flare and disable it now
  64218. 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);
  64219. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  64220. }
  64221. if (this._hdrEnabled) {
  64222. // Create luminance
  64223. this._createLuminancePostProcesses(scene, this._floatTextureType);
  64224. // Create HDR
  64225. this._createHdrPostProcess(scene, ratio);
  64226. // Create depth-of-field source post-process post hdr and disable it now
  64227. 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);
  64228. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  64229. }
  64230. if (this._depthOfFieldEnabled) {
  64231. // Create gaussian blur used by depth-of-field
  64232. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  64233. // Create depth-of-field post-process
  64234. this._createDepthOfFieldPostProcess(scene, ratio);
  64235. }
  64236. if (this._motionBlurEnabled) {
  64237. // Create motion blur post-process
  64238. this._createMotionBlurPostProcess(scene, ratio);
  64239. }
  64240. if (this._cameras !== null) {
  64241. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  64242. }
  64243. };
  64244. // Down Sample X4 Post-Processs
  64245. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  64246. var _this = this;
  64247. var downSampleX4Offsets = new Array(32);
  64248. 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);
  64249. this.downSampleX4PostProcess.onApply = function (effect) {
  64250. var id = 0;
  64251. var width = _this.downSampleX4PostProcess.width;
  64252. var height = _this.downSampleX4PostProcess.height;
  64253. for (var i = -2; i < 2; i++) {
  64254. for (var j = -2; j < 2; j++) {
  64255. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  64256. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  64257. id += 2;
  64258. }
  64259. }
  64260. effect.setArray2("dsOffsets", downSampleX4Offsets);
  64261. };
  64262. // Add to pipeline
  64263. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  64264. };
  64265. // Brightpass Post-Process
  64266. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  64267. var _this = this;
  64268. var brightOffsets = new Array(8);
  64269. 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);
  64270. this.brightPassPostProcess.onApply = function (effect) {
  64271. var sU = (1.0 / _this.brightPassPostProcess.width);
  64272. var sV = (1.0 / _this.brightPassPostProcess.height);
  64273. brightOffsets[0] = -0.5 * sU;
  64274. brightOffsets[1] = 0.5 * sV;
  64275. brightOffsets[2] = 0.5 * sU;
  64276. brightOffsets[3] = 0.5 * sV;
  64277. brightOffsets[4] = -0.5 * sU;
  64278. brightOffsets[5] = -0.5 * sV;
  64279. brightOffsets[6] = 0.5 * sU;
  64280. brightOffsets[7] = -0.5 * sV;
  64281. effect.setArray2("dsOffsets", brightOffsets);
  64282. effect.setFloat("brightThreshold", _this.brightThreshold);
  64283. };
  64284. // Add to pipeline
  64285. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  64286. };
  64287. // Create blur H&V post-processes
  64288. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  64289. var _this = this;
  64290. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  64291. var engine = scene.getEngine();
  64292. 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);
  64293. 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);
  64294. blurX.onActivateObservable.add(function () {
  64295. var dw = blurX.width / engine.getRenderWidth();
  64296. blurX.kernel = _this[blurWidthKey] * dw;
  64297. });
  64298. blurY.onActivateObservable.add(function () {
  64299. var dw = blurY.height / engine.getRenderHeight();
  64300. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  64301. });
  64302. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  64303. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  64304. this.blurHPostProcesses.push(blurX);
  64305. this.blurVPostProcesses.push(blurY);
  64306. };
  64307. // Create texture adder post-process
  64308. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  64309. var _this = this;
  64310. 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);
  64311. this.textureAdderPostProcess.onApply = function (effect) {
  64312. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  64313. effect.setTexture("lensSampler", _this.lensTexture);
  64314. effect.setFloat("exposure", _this.exposure);
  64315. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  64316. };
  64317. // Add to pipeline
  64318. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  64319. };
  64320. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  64321. var _this = this;
  64322. var geometryRenderer = scene.enableGeometryBufferRenderer();
  64323. geometryRenderer.enablePosition = true;
  64324. var geometry = geometryRenderer.getGBuffer();
  64325. // Base post-process
  64326. 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));
  64327. var depthValues = BABYLON.Vector2.Zero();
  64328. this.volumetricLightPostProcess.onApply = function (effect) {
  64329. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  64330. var generator = _this.sourceLight.getShadowGenerator();
  64331. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  64332. effect.setTexture("positionSampler", geometry.textures[2]);
  64333. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  64334. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  64335. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  64336. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  64337. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  64338. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  64339. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  64340. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  64341. effect.setVector2("depthValues", depthValues);
  64342. }
  64343. };
  64344. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  64345. // Smooth
  64346. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  64347. // Merge
  64348. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  64349. this.volumetricLightMergePostProces.onApply = function (effect) {
  64350. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  64351. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  64352. };
  64353. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  64354. };
  64355. // Create luminance
  64356. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  64357. var _this = this;
  64358. // Create luminance
  64359. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  64360. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  64361. var offsets = [];
  64362. this.luminancePostProcess.onApply = function (effect) {
  64363. var sU = (1.0 / _this.luminancePostProcess.width);
  64364. var sV = (1.0 / _this.luminancePostProcess.height);
  64365. offsets[0] = -0.5 * sU;
  64366. offsets[1] = 0.5 * sV;
  64367. offsets[2] = 0.5 * sU;
  64368. offsets[3] = 0.5 * sV;
  64369. offsets[4] = -0.5 * sU;
  64370. offsets[5] = -0.5 * sV;
  64371. offsets[6] = 0.5 * sU;
  64372. offsets[7] = -0.5 * sV;
  64373. effect.setArray2("lumOffsets", offsets);
  64374. };
  64375. // Add to pipeline
  64376. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  64377. // Create down sample luminance
  64378. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  64379. var size = Math.pow(3, i);
  64380. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  64381. if (i === 0) {
  64382. defines += "#define FINAL_DOWN_SAMPLER";
  64383. }
  64384. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  64385. this.luminanceDownSamplePostProcesses.push(postProcess);
  64386. }
  64387. // Create callbacks and add effects
  64388. var lastLuminance = this.luminancePostProcess;
  64389. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  64390. var downSampleOffsets = new Array(18);
  64391. pp.onApply = function (effect) {
  64392. if (!lastLuminance) {
  64393. return;
  64394. }
  64395. var id = 0;
  64396. for (var x = -1; x < 2; x++) {
  64397. for (var y = -1; y < 2; y++) {
  64398. downSampleOffsets[id] = x / lastLuminance.width;
  64399. downSampleOffsets[id + 1] = y / lastLuminance.height;
  64400. id += 2;
  64401. }
  64402. }
  64403. effect.setArray2("dsOffsets", downSampleOffsets);
  64404. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  64405. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  64406. lastLuminance = _this.luminancePostProcess;
  64407. }
  64408. else {
  64409. lastLuminance = pp;
  64410. }
  64411. };
  64412. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  64413. pp.onAfterRender = function (effect) {
  64414. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  64415. 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);
  64416. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  64417. };
  64418. }
  64419. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  64420. });
  64421. };
  64422. // Create HDR post-process
  64423. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  64424. var _this = this;
  64425. 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);
  64426. var outputLiminance = 1;
  64427. var time = 0;
  64428. var lastTime = 0;
  64429. this.hdrPostProcess.onApply = function (effect) {
  64430. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  64431. time += scene.getEngine().getDeltaTime();
  64432. if (outputLiminance < 0) {
  64433. outputLiminance = _this._hdrCurrentLuminance;
  64434. }
  64435. else {
  64436. var dt = (lastTime - time) / 1000.0;
  64437. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  64438. outputLiminance += _this.hdrDecreaseRate * dt;
  64439. }
  64440. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  64441. outputLiminance -= _this.hdrIncreaseRate * dt;
  64442. }
  64443. else {
  64444. outputLiminance = _this._hdrCurrentLuminance;
  64445. }
  64446. }
  64447. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  64448. effect.setFloat("averageLuminance", outputLiminance);
  64449. lastTime = time;
  64450. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  64451. };
  64452. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  64453. };
  64454. // Create lens flare post-process
  64455. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  64456. var _this = this;
  64457. 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);
  64458. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  64459. this._createBlurPostProcesses(scene, ratio / 4, 2);
  64460. 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);
  64461. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  64462. var resolution = new BABYLON.Vector2(0, 0);
  64463. // Lens flare
  64464. this.lensFlarePostProcess.onApply = function (effect) {
  64465. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  64466. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  64467. effect.setFloat("strength", _this.lensFlareStrength);
  64468. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  64469. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  64470. // Shift
  64471. resolution.x = _this.lensFlarePostProcess.width;
  64472. resolution.y = _this.lensFlarePostProcess.height;
  64473. effect.setVector2("resolution", resolution);
  64474. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  64475. };
  64476. // Compose
  64477. 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);
  64478. 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);
  64479. this.lensFlareComposePostProcess.onApply = function (effect) {
  64480. if (!_this._scene.activeCamera) {
  64481. return;
  64482. }
  64483. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  64484. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  64485. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  64486. // Lens start rotation matrix
  64487. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  64488. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  64489. 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));
  64490. camRot *= 4.0;
  64491. 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);
  64492. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  64493. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  64494. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  64495. };
  64496. };
  64497. // Create depth-of-field post-process
  64498. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  64499. var _this = this;
  64500. 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);
  64501. this.depthOfFieldPostProcess.onApply = function (effect) {
  64502. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  64503. effect.setTexture("depthSampler", _this._getDepthTexture());
  64504. effect.setFloat("distance", _this.depthOfFieldDistance);
  64505. };
  64506. // Add to pipeline
  64507. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  64508. };
  64509. // Create motion blur post-process
  64510. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  64511. var _this = this;
  64512. 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);
  64513. var motionScale = 0;
  64514. var prevViewProjection = BABYLON.Matrix.Identity();
  64515. var invViewProjection = BABYLON.Matrix.Identity();
  64516. var viewProjection = BABYLON.Matrix.Identity();
  64517. var screenSize = BABYLON.Vector2.Zero();
  64518. this.motionBlurPostProcess.onApply = function (effect) {
  64519. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  64520. viewProjection.invertToRef(invViewProjection);
  64521. effect.setMatrix("inverseViewProjection", invViewProjection);
  64522. effect.setMatrix("prevViewProjection", prevViewProjection);
  64523. prevViewProjection = viewProjection;
  64524. screenSize.x = _this.motionBlurPostProcess.width;
  64525. screenSize.y = _this.motionBlurPostProcess.height;
  64526. effect.setVector2("screenSize", screenSize);
  64527. motionScale = scene.getEngine().getFps() / 60.0;
  64528. effect.setFloat("motionScale", motionScale);
  64529. effect.setFloat("motionStrength", _this.motionStrength);
  64530. effect.setTexture("depthSampler", _this._getDepthTexture());
  64531. };
  64532. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  64533. };
  64534. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  64535. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  64536. var renderer = this._scene.enableGeometryBufferRenderer();
  64537. return renderer.getGBuffer().textures[0];
  64538. }
  64539. return this._scene.enableDepthRenderer().getDepthMap();
  64540. };
  64541. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  64542. for (var i = 0; i < this._cameras.length; i++) {
  64543. var camera = this._cameras[i];
  64544. if (this.originalPostProcess) {
  64545. this.originalPostProcess.dispose(camera);
  64546. }
  64547. if (this.downSampleX4PostProcess) {
  64548. this.downSampleX4PostProcess.dispose(camera);
  64549. }
  64550. if (this.brightPassPostProcess) {
  64551. this.brightPassPostProcess.dispose(camera);
  64552. }
  64553. if (this.textureAdderPostProcess) {
  64554. this.textureAdderPostProcess.dispose(camera);
  64555. }
  64556. if (this.textureAdderFinalPostProcess) {
  64557. this.textureAdderFinalPostProcess.dispose(camera);
  64558. }
  64559. if (this.volumetricLightPostProcess) {
  64560. this.volumetricLightPostProcess.dispose(camera);
  64561. }
  64562. if (this.volumetricLightSmoothXPostProcess) {
  64563. this.volumetricLightSmoothXPostProcess.dispose(camera);
  64564. }
  64565. if (this.volumetricLightSmoothYPostProcess) {
  64566. this.volumetricLightSmoothYPostProcess.dispose(camera);
  64567. }
  64568. if (this.volumetricLightMergePostProces) {
  64569. this.volumetricLightMergePostProces.dispose(camera);
  64570. }
  64571. if (this.volumetricLightFinalPostProcess) {
  64572. this.volumetricLightFinalPostProcess.dispose(camera);
  64573. }
  64574. if (this.lensFlarePostProcess) {
  64575. this.lensFlarePostProcess.dispose(camera);
  64576. }
  64577. if (this.lensFlareComposePostProcess) {
  64578. this.lensFlareComposePostProcess.dispose(camera);
  64579. }
  64580. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  64581. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  64582. }
  64583. if (this.luminancePostProcess) {
  64584. this.luminancePostProcess.dispose(camera);
  64585. }
  64586. if (this.hdrPostProcess) {
  64587. this.hdrPostProcess.dispose(camera);
  64588. }
  64589. if (this.hdrFinalPostProcess) {
  64590. this.hdrFinalPostProcess.dispose(camera);
  64591. }
  64592. if (this.depthOfFieldPostProcess) {
  64593. this.depthOfFieldPostProcess.dispose(camera);
  64594. }
  64595. if (this.motionBlurPostProcess) {
  64596. this.motionBlurPostProcess.dispose(camera);
  64597. }
  64598. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  64599. this.blurHPostProcesses[j].dispose(camera);
  64600. }
  64601. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  64602. this.blurVPostProcesses[j].dispose(camera);
  64603. }
  64604. }
  64605. this.originalPostProcess = null;
  64606. this.downSampleX4PostProcess = null;
  64607. this.brightPassPostProcess = null;
  64608. this.textureAdderPostProcess = null;
  64609. this.textureAdderFinalPostProcess = null;
  64610. this.volumetricLightPostProcess = null;
  64611. this.volumetricLightSmoothXPostProcess = null;
  64612. this.volumetricLightSmoothYPostProcess = null;
  64613. this.volumetricLightMergePostProces = null;
  64614. this.volumetricLightFinalPostProcess = null;
  64615. this.lensFlarePostProcess = null;
  64616. this.lensFlareComposePostProcess = null;
  64617. this.luminancePostProcess = null;
  64618. this.hdrPostProcess = null;
  64619. this.hdrFinalPostProcess = null;
  64620. this.depthOfFieldPostProcess = null;
  64621. this.motionBlurPostProcess = null;
  64622. this.luminanceDownSamplePostProcesses = [];
  64623. this.blurHPostProcesses = [];
  64624. this.blurVPostProcesses = [];
  64625. };
  64626. // Dispose
  64627. StandardRenderingPipeline.prototype.dispose = function () {
  64628. this._disposePostProcesses();
  64629. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  64630. _super.prototype.dispose.call(this);
  64631. };
  64632. // Serialize rendering pipeline
  64633. StandardRenderingPipeline.prototype.serialize = function () {
  64634. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64635. serializationObject.customType = "StandardRenderingPipeline";
  64636. return serializationObject;
  64637. };
  64638. /**
  64639. * Static members
  64640. */
  64641. // Parse serialized pipeline
  64642. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  64643. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  64644. };
  64645. // Luminance steps
  64646. StandardRenderingPipeline.LuminanceSteps = 6;
  64647. __decorate([
  64648. BABYLON.serialize()
  64649. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  64650. __decorate([
  64651. BABYLON.serialize()
  64652. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  64653. __decorate([
  64654. BABYLON.serialize()
  64655. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  64656. __decorate([
  64657. BABYLON.serialize()
  64658. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  64659. __decorate([
  64660. BABYLON.serializeAsTexture("lensTexture")
  64661. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  64662. __decorate([
  64663. BABYLON.serialize()
  64664. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  64665. __decorate([
  64666. BABYLON.serialize()
  64667. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  64668. __decorate([
  64669. BABYLON.serialize()
  64670. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  64671. __decorate([
  64672. BABYLON.serialize()
  64673. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  64674. __decorate([
  64675. BABYLON.serialize()
  64676. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  64677. __decorate([
  64678. BABYLON.serialize()
  64679. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  64680. __decorate([
  64681. BABYLON.serializeAsTexture("lensColorTexture")
  64682. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  64683. __decorate([
  64684. BABYLON.serialize()
  64685. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  64686. __decorate([
  64687. BABYLON.serialize()
  64688. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  64689. __decorate([
  64690. BABYLON.serialize()
  64691. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  64692. __decorate([
  64693. BABYLON.serialize()
  64694. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  64695. __decorate([
  64696. BABYLON.serializeAsTexture("lensStarTexture")
  64697. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  64698. __decorate([
  64699. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  64700. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  64701. __decorate([
  64702. BABYLON.serialize()
  64703. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  64704. __decorate([
  64705. BABYLON.serialize()
  64706. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  64707. __decorate([
  64708. BABYLON.serialize()
  64709. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  64710. __decorate([
  64711. BABYLON.serialize()
  64712. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  64713. __decorate([
  64714. BABYLON.serialize()
  64715. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  64716. __decorate([
  64717. BABYLON.serialize()
  64718. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  64719. __decorate([
  64720. BABYLON.serialize()
  64721. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  64722. __decorate([
  64723. BABYLON.serialize()
  64724. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  64725. __decorate([
  64726. BABYLON.serialize()
  64727. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  64728. __decorate([
  64729. BABYLON.serialize()
  64730. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  64731. __decorate([
  64732. BABYLON.serialize()
  64733. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  64734. __decorate([
  64735. BABYLON.serialize()
  64736. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  64737. return StandardRenderingPipeline;
  64738. }(BABYLON.PostProcessRenderPipeline));
  64739. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  64740. })(BABYLON || (BABYLON = {}));
  64741. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  64742. var BABYLON;
  64743. (function (BABYLON) {
  64744. var FxaaPostProcess = /** @class */ (function (_super) {
  64745. __extends(FxaaPostProcess, _super);
  64746. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64747. if (camera === void 0) { camera = null; }
  64748. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64749. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  64750. _this.onApplyObservable.add(function (effect) {
  64751. var texelSize = _this.texelSize;
  64752. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  64753. });
  64754. return _this;
  64755. }
  64756. return FxaaPostProcess;
  64757. }(BABYLON.PostProcess));
  64758. BABYLON.FxaaPostProcess = FxaaPostProcess;
  64759. })(BABYLON || (BABYLON = {}));
  64760. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  64761. var BABYLON;
  64762. (function (BABYLON) {
  64763. /**
  64764. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  64765. */
  64766. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  64767. __extends(CircleOfConfusionPostProcess, _super);
  64768. /**
  64769. * Creates a new instance of @see CircleOfConfusionPostProcess
  64770. * @param name The name of the effect.
  64771. * @param scene The scene the effect belongs to.
  64772. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  64773. * @param options The required width/height ratio to downsize to before computing the render pass.
  64774. * @param camera The camera to apply the render pass to.
  64775. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64776. * @param engine The engine which the post process will be applied. (default: current engine)
  64777. * @param reusable If the post process can be reused on the same frame. (default: false)
  64778. * @param textureType Type of textures used when performing the post process. (default: 0)
  64779. */
  64780. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  64781. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64782. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64783. /**
  64784. * 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.
  64785. */
  64786. _this.lensSize = 50;
  64787. /**
  64788. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64789. */
  64790. _this.fStop = 1.4;
  64791. /**
  64792. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64793. */
  64794. _this.focusDistance = 2000;
  64795. /**
  64796. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  64797. */
  64798. _this.focalLength = 50;
  64799. _this.onApplyObservable.add(function (effect) {
  64800. effect.setTexture("depthSampler", depthTexture);
  64801. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  64802. var aperture = _this.lensSize / _this.fStop;
  64803. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  64804. effect.setFloat('focusDistance', _this.focusDistance);
  64805. effect.setFloat('cocPrecalculation', cocPrecalculation);
  64806. if (scene.activeCamera) {
  64807. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  64808. }
  64809. });
  64810. return _this;
  64811. }
  64812. return CircleOfConfusionPostProcess;
  64813. }(BABYLON.PostProcess));
  64814. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  64815. })(BABYLON || (BABYLON = {}));
  64816. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  64817. var BABYLON;
  64818. (function (BABYLON) {
  64819. /**
  64820. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  64821. */
  64822. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  64823. __extends(DepthOfFieldMergePostProcess, _super);
  64824. /**
  64825. * Creates a new instance of @see CircleOfConfusionPostProcess
  64826. * @param name The name of the effect.
  64827. * @param original The non-blurred image to be modified
  64828. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  64829. * @param options The required width/height ratio to downsize to before computing the render pass.
  64830. * @param camera The camera to apply the render pass to.
  64831. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64832. * @param engine The engine which the post process will be applied. (default: current engine)
  64833. * @param reusable If the post process can be reused on the same frame. (default: false)
  64834. * @param textureType Type of textures used when performing the post process. (default: 0)
  64835. */
  64836. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, options, camera, samplingMode, engine, reusable, textureType) {
  64837. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64838. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64839. _this.onApplyObservable.add(function (effect) {
  64840. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  64841. effect.setTextureFromPostProcess("originalSampler", original);
  64842. });
  64843. return _this;
  64844. }
  64845. return DepthOfFieldMergePostProcess;
  64846. }(BABYLON.PostProcess));
  64847. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  64848. })(BABYLON || (BABYLON = {}));
  64849. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  64850. var BABYLON;
  64851. (function (BABYLON) {
  64852. /**
  64853. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  64854. */
  64855. var DepthOfFieldEffect = /** @class */ (function (_super) {
  64856. __extends(DepthOfFieldEffect, _super);
  64857. /**
  64858. * Creates a new instance of @see DepthOfFieldEffect
  64859. * @param scene The scene the effect belongs to.
  64860. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  64861. */
  64862. function DepthOfFieldEffect(scene, pipelineTextureType) {
  64863. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  64864. var _this = _super.call(this, scene.getEngine(), "depth of field", function () { return [_this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY, _this._depthOfFieldBlurX, _this._depthOfFieldMerge]; }, true) || this;
  64865. // Enable and get current depth map
  64866. var depthMap = scene.enableDepthRenderer().getDepthMap();
  64867. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  64868. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64869. // Capture circle of confusion texture
  64870. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64871. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  64872. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  64873. _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);
  64874. _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);
  64875. // Merge blurred images with original image based on circleOfConfusion
  64876. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64877. return _this;
  64878. }
  64879. Object.defineProperty(DepthOfFieldEffect.prototype, "kernelSize", {
  64880. get: function () {
  64881. return this._depthOfFieldBlurX.kernel;
  64882. },
  64883. /**
  64884. * The size of the kernel to be used for the blur
  64885. */
  64886. set: function (value) {
  64887. this._depthOfFieldBlurX.kernel = value;
  64888. this._depthOfFieldBlurY.kernel = value;
  64889. },
  64890. enumerable: true,
  64891. configurable: true
  64892. });
  64893. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  64894. get: function () {
  64895. return this._circleOfConfusion.focalLength;
  64896. },
  64897. /**
  64898. * The focal the length of the camera used in the effect
  64899. */
  64900. set: function (value) {
  64901. this._circleOfConfusion.focalLength = value;
  64902. },
  64903. enumerable: true,
  64904. configurable: true
  64905. });
  64906. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  64907. get: function () {
  64908. return this._circleOfConfusion.fStop;
  64909. },
  64910. /**
  64911. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64912. */
  64913. set: function (value) {
  64914. this._circleOfConfusion.fStop = value;
  64915. },
  64916. enumerable: true,
  64917. configurable: true
  64918. });
  64919. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  64920. get: function () {
  64921. return this._circleOfConfusion.focusDistance;
  64922. },
  64923. /**
  64924. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64925. */
  64926. set: function (value) {
  64927. this._circleOfConfusion.focusDistance = value;
  64928. },
  64929. enumerable: true,
  64930. configurable: true
  64931. });
  64932. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  64933. get: function () {
  64934. return this._circleOfConfusion.lensSize;
  64935. },
  64936. /**
  64937. * 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.
  64938. */
  64939. set: function (value) {
  64940. this._circleOfConfusion.lensSize = value;
  64941. },
  64942. enumerable: true,
  64943. configurable: true
  64944. });
  64945. /**
  64946. * Disposes each of the internal effects for a given camera.
  64947. * @param camera The camera to dispose the effect on.
  64948. */
  64949. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  64950. this._depthOfFieldPass.dispose(camera);
  64951. this._circleOfConfusion.dispose(camera);
  64952. this._depthOfFieldBlurX.dispose(camera);
  64953. this._depthOfFieldBlurY.dispose(camera);
  64954. this._depthOfFieldMerge.dispose(camera);
  64955. };
  64956. return DepthOfFieldEffect;
  64957. }(BABYLON.PostProcessRenderEffect));
  64958. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  64959. })(BABYLON || (BABYLON = {}));
  64960. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  64961. var BABYLON;
  64962. (function (BABYLON) {
  64963. /**
  64964. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  64965. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  64966. */
  64967. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  64968. __extends(DefaultRenderingPipeline, _super);
  64969. /**
  64970. * @constructor
  64971. * @param {string} name - The rendering pipeline name
  64972. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64973. * @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)
  64974. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64975. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  64976. */
  64977. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  64978. if (automaticBuild === void 0) { automaticBuild = true; }
  64979. var _this = _super.call(this, scene.getEngine(), name) || this;
  64980. /**
  64981. * ID of the pass post process used for bloom,
  64982. */
  64983. _this.PassPostProcessId = "PassPostProcessEffect";
  64984. /**
  64985. * ID of the highlight post process used for bloom,
  64986. */
  64987. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  64988. /**
  64989. * ID of the blurX post process used for bloom,
  64990. */
  64991. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  64992. /**
  64993. * ID of the blurY post process used for bloom,
  64994. */
  64995. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  64996. /**
  64997. * ID of the copy back post process used for bloom,
  64998. */
  64999. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  65000. /**
  65001. * ID of the image processing post process;
  65002. */
  65003. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  65004. /**
  65005. * ID of the Fast Approximate Anti-Aliasing post process;
  65006. */
  65007. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  65008. /**
  65009. * ID of the final merge post process;
  65010. */
  65011. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  65012. /**
  65013. * Animations which can be used to tweak settings over a period of time
  65014. */
  65015. _this.animations = [];
  65016. // Values
  65017. _this._bloomEnabled = false;
  65018. _this._depthOfFieldEnabled = false;
  65019. _this._fxaaEnabled = false;
  65020. _this._imageProcessingEnabled = true;
  65021. _this._bloomScale = 0.6;
  65022. _this._buildAllowed = true;
  65023. /**
  65024. * Specifies the size of the bloom blur kernel, relative to the final output size
  65025. */
  65026. _this.bloomKernel = 64;
  65027. /**
  65028. * Specifies the weight of the bloom in the final rendering
  65029. */
  65030. _this._bloomWeight = 0.15;
  65031. _this._cameras = cameras || [];
  65032. _this._buildAllowed = automaticBuild;
  65033. // Initialize
  65034. _this._scene = scene;
  65035. var caps = _this._scene.getEngine().getCaps();
  65036. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  65037. // Misc
  65038. if (_this._hdr) {
  65039. if (caps.textureHalfFloatRender) {
  65040. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65041. }
  65042. else if (caps.textureFloatRender) {
  65043. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65044. }
  65045. }
  65046. else {
  65047. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65048. }
  65049. // Attach
  65050. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65051. _this._buildPipeline();
  65052. return _this;
  65053. }
  65054. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  65055. get: function () {
  65056. return this._bloomWeight;
  65057. },
  65058. /**
  65059. * The strength of the bloom.
  65060. */
  65061. set: function (value) {
  65062. if (this._bloomWeight === value) {
  65063. return;
  65064. }
  65065. this._bloomWeight = value;
  65066. if (this._hdr && this.copyBack) {
  65067. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  65068. }
  65069. },
  65070. enumerable: true,
  65071. configurable: true
  65072. });
  65073. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  65074. get: function () {
  65075. return this._bloomScale;
  65076. },
  65077. /**
  65078. * The scale of the bloom, lower value will provide better performance.
  65079. */
  65080. set: function (value) {
  65081. if (this._bloomScale === value) {
  65082. return;
  65083. }
  65084. this._bloomScale = value;
  65085. this._buildPipeline();
  65086. },
  65087. enumerable: true,
  65088. configurable: true
  65089. });
  65090. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  65091. get: function () {
  65092. return this._bloomEnabled;
  65093. },
  65094. /**
  65095. * Enable or disable the bloom from the pipeline
  65096. */
  65097. set: function (enabled) {
  65098. if (this._bloomEnabled === enabled) {
  65099. return;
  65100. }
  65101. this._bloomEnabled = enabled;
  65102. this._buildPipeline();
  65103. },
  65104. enumerable: true,
  65105. configurable: true
  65106. });
  65107. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  65108. /**
  65109. * If the depth of field is enabled.
  65110. */
  65111. get: function () {
  65112. return this._depthOfFieldEnabled;
  65113. },
  65114. set: function (enabled) {
  65115. if (this._depthOfFieldEnabled === enabled) {
  65116. return;
  65117. }
  65118. this._depthOfFieldEnabled = enabled;
  65119. this._buildPipeline();
  65120. },
  65121. enumerable: true,
  65122. configurable: true
  65123. });
  65124. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  65125. get: function () {
  65126. return this._fxaaEnabled;
  65127. },
  65128. /**
  65129. * If the anti aliasing is enabled.
  65130. */
  65131. set: function (enabled) {
  65132. if (this._fxaaEnabled === enabled) {
  65133. return;
  65134. }
  65135. this._fxaaEnabled = enabled;
  65136. this._buildPipeline();
  65137. },
  65138. enumerable: true,
  65139. configurable: true
  65140. });
  65141. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  65142. get: function () {
  65143. return this._imageProcessingEnabled;
  65144. },
  65145. /**
  65146. * If image processing is enabled.
  65147. */
  65148. set: function (enabled) {
  65149. if (this._imageProcessingEnabled === enabled) {
  65150. return;
  65151. }
  65152. this._imageProcessingEnabled = enabled;
  65153. this._buildPipeline();
  65154. },
  65155. enumerable: true,
  65156. configurable: true
  65157. });
  65158. /**
  65159. * Force the compilation of the entire pipeline.
  65160. */
  65161. DefaultRenderingPipeline.prototype.prepare = function () {
  65162. var previousState = this._buildAllowed;
  65163. this._buildAllowed = true;
  65164. this._buildPipeline();
  65165. this._buildAllowed = previousState;
  65166. };
  65167. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  65168. var _this = this;
  65169. if (!this._buildAllowed) {
  65170. return;
  65171. }
  65172. var engine = this._scene.getEngine();
  65173. this._disposePostProcesses();
  65174. this._reset();
  65175. if (this.bloomEnabled) {
  65176. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  65177. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  65178. if (!this._hdr) {
  65179. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  65180. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  65181. this.highlights.autoClear = false;
  65182. this.highlights.alwaysForcePOT = true;
  65183. }
  65184. 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);
  65185. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  65186. this.blurX.alwaysForcePOT = true;
  65187. this.blurX.autoClear = false;
  65188. this.blurX.onActivateObservable.add(function () {
  65189. var dw = _this.blurX.width / engine.getRenderWidth(true);
  65190. _this.blurX.kernel = _this.bloomKernel * dw;
  65191. });
  65192. 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);
  65193. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  65194. this.blurY.alwaysForcePOT = true;
  65195. this.blurY.autoClear = false;
  65196. this.blurY.onActivateObservable.add(function () {
  65197. var dh = _this.blurY.height / engine.getRenderHeight(true);
  65198. _this.blurY.kernel = _this.bloomKernel * dh;
  65199. });
  65200. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  65201. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  65202. this.copyBack.alwaysForcePOT = true;
  65203. if (this._hdr) {
  65204. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  65205. var w = this.bloomWeight;
  65206. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  65207. }
  65208. else {
  65209. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  65210. }
  65211. this.copyBack.autoClear = false;
  65212. }
  65213. if (this.depthOfFieldEnabled) {
  65214. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._defaultPipelineTextureType);
  65215. this.addEffect(this.depthOfField);
  65216. }
  65217. if (this._imageProcessingEnabled) {
  65218. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  65219. if (this._hdr) {
  65220. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  65221. }
  65222. else {
  65223. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  65224. }
  65225. }
  65226. if (this.fxaaEnabled) {
  65227. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  65228. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  65229. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  65230. }
  65231. else if (this._hdr && this.imageProcessing) {
  65232. this.finalMerge = this.imageProcessing;
  65233. }
  65234. else {
  65235. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  65236. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  65237. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  65238. }
  65239. if (this.bloomEnabled) {
  65240. if (this._hdr) {
  65241. this.copyBack.shareOutputWith(this.blurX);
  65242. if (this.imageProcessing) {
  65243. this.imageProcessing.shareOutputWith(this.pass);
  65244. this.imageProcessing.autoClear = false;
  65245. }
  65246. else if (this.fxaa) {
  65247. this.fxaa.shareOutputWith(this.pass);
  65248. }
  65249. else {
  65250. this.finalMerge.shareOutputWith(this.pass);
  65251. }
  65252. }
  65253. else {
  65254. if (this.fxaa) {
  65255. this.fxaa.shareOutputWith(this.pass);
  65256. }
  65257. else {
  65258. this.finalMerge.shareOutputWith(this.pass);
  65259. }
  65260. }
  65261. }
  65262. if (this._cameras !== null) {
  65263. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  65264. }
  65265. };
  65266. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  65267. for (var i = 0; i < this._cameras.length; i++) {
  65268. var camera = this._cameras[i];
  65269. if (this.pass) {
  65270. this.pass.dispose(camera);
  65271. }
  65272. if (this.highlights) {
  65273. this.highlights.dispose(camera);
  65274. }
  65275. if (this.blurX) {
  65276. this.blurX.dispose(camera);
  65277. }
  65278. if (this.blurY) {
  65279. this.blurY.dispose(camera);
  65280. }
  65281. if (this.copyBack) {
  65282. this.copyBack.dispose(camera);
  65283. }
  65284. if (this.imageProcessing) {
  65285. this.imageProcessing.dispose(camera);
  65286. }
  65287. if (this.fxaa) {
  65288. this.fxaa.dispose(camera);
  65289. }
  65290. if (this.finalMerge) {
  65291. this.finalMerge.dispose(camera);
  65292. }
  65293. if (this.depthOfField) {
  65294. this.depthOfField.disposeEffects(camera);
  65295. }
  65296. }
  65297. this.pass = null;
  65298. this.highlights = null;
  65299. this.blurX = null;
  65300. this.blurY = null;
  65301. this.copyBack = null;
  65302. this.imageProcessing = null;
  65303. this.fxaa = null;
  65304. this.finalMerge = null;
  65305. this.depthOfField = null;
  65306. };
  65307. /**
  65308. * Dispose of the pipeline and stop all post processes
  65309. */
  65310. DefaultRenderingPipeline.prototype.dispose = function () {
  65311. this._disposePostProcesses();
  65312. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  65313. _super.prototype.dispose.call(this);
  65314. };
  65315. /**
  65316. * Serialize the rendering pipeline (Used when exporting)
  65317. * @returns the serialized object
  65318. */
  65319. DefaultRenderingPipeline.prototype.serialize = function () {
  65320. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  65321. serializationObject.customType = "DefaultRenderingPipeline";
  65322. return serializationObject;
  65323. };
  65324. /**
  65325. * Parse the serialized pipeline
  65326. * @param source Source pipeline.
  65327. * @param scene The scene to load the pipeline to.
  65328. * @param rootUrl The URL of the serialized pipeline.
  65329. * @returns An instantiated pipeline from the serialized object.
  65330. */
  65331. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  65332. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  65333. };
  65334. __decorate([
  65335. BABYLON.serialize()
  65336. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  65337. __decorate([
  65338. BABYLON.serialize()
  65339. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  65340. __decorate([
  65341. BABYLON.serialize()
  65342. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  65343. __decorate([
  65344. BABYLON.serialize()
  65345. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  65346. __decorate([
  65347. BABYLON.serialize()
  65348. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  65349. __decorate([
  65350. BABYLON.serialize()
  65351. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  65352. __decorate([
  65353. BABYLON.serialize()
  65354. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  65355. __decorate([
  65356. BABYLON.serialize()
  65357. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  65358. __decorate([
  65359. BABYLON.serialize()
  65360. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  65361. return DefaultRenderingPipeline;
  65362. }(BABYLON.PostProcessRenderPipeline));
  65363. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  65364. })(BABYLON || (BABYLON = {}));
  65365. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  65366. var BABYLON;
  65367. (function (BABYLON) {
  65368. /**
  65369. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  65370. */
  65371. var GeometryBufferRenderer = /** @class */ (function () {
  65372. /**
  65373. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  65374. * @param scene The scene the buffer belongs to
  65375. * @param ratio How big is the buffer related to the main canvas.
  65376. */
  65377. function GeometryBufferRenderer(scene, ratio) {
  65378. if (ratio === void 0) { ratio = 1; }
  65379. this._enablePosition = false;
  65380. this._scene = scene;
  65381. this._ratio = ratio;
  65382. // Render target
  65383. this._createRenderTargets();
  65384. }
  65385. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  65386. /**
  65387. * Set the render list (meshes to be rendered) used in the G buffer.
  65388. */
  65389. set: function (meshes) {
  65390. this._multiRenderTarget.renderList = meshes;
  65391. },
  65392. enumerable: true,
  65393. configurable: true
  65394. });
  65395. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  65396. /**
  65397. * Gets wether or not G buffer are supported by the running hardware.
  65398. * This requires draw buffer supports
  65399. */
  65400. get: function () {
  65401. return this._multiRenderTarget.isSupported;
  65402. },
  65403. enumerable: true,
  65404. configurable: true
  65405. });
  65406. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  65407. /**
  65408. * Gets wether or not position are enabled for the G buffer.
  65409. */
  65410. get: function () {
  65411. return this._enablePosition;
  65412. },
  65413. /**
  65414. * Sets wether or not position are enabled for the G buffer.
  65415. */
  65416. set: function (enable) {
  65417. this._enablePosition = enable;
  65418. this.dispose();
  65419. this._createRenderTargets();
  65420. },
  65421. enumerable: true,
  65422. configurable: true
  65423. });
  65424. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  65425. /**
  65426. * Gets the scene associated with the buffer.
  65427. */
  65428. get: function () {
  65429. return this._scene;
  65430. },
  65431. enumerable: true,
  65432. configurable: true
  65433. });
  65434. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  65435. /**
  65436. * Gets the ratio used by the buffer during its creation.
  65437. * How big is the buffer related to the main canvas.
  65438. */
  65439. get: function () {
  65440. return this._ratio;
  65441. },
  65442. enumerable: true,
  65443. configurable: true
  65444. });
  65445. /**
  65446. * Checks wether everything is ready to render a submesh to the G buffer.
  65447. * @param subMesh the submesh to check readiness for
  65448. * @param useInstances is the mesh drawn using instance or not
  65449. * @returns true if ready otherwise false
  65450. */
  65451. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  65452. var material = subMesh.getMaterial();
  65453. if (material && material.disableDepthWrite) {
  65454. return false;
  65455. }
  65456. var defines = [];
  65457. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  65458. var mesh = subMesh.getMesh();
  65459. // Alpha test
  65460. if (material && material.needAlphaTesting()) {
  65461. defines.push("#define ALPHATEST");
  65462. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65463. attribs.push(BABYLON.VertexBuffer.UVKind);
  65464. defines.push("#define UV1");
  65465. }
  65466. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65467. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65468. defines.push("#define UV2");
  65469. }
  65470. }
  65471. // Buffers
  65472. if (this._enablePosition) {
  65473. defines.push("#define POSITION");
  65474. }
  65475. // Bones
  65476. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65477. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65478. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65479. if (mesh.numBoneInfluencers > 4) {
  65480. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65481. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65482. }
  65483. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65484. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  65485. }
  65486. else {
  65487. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65488. }
  65489. // Instances
  65490. if (useInstances) {
  65491. defines.push("#define INSTANCES");
  65492. attribs.push("world0");
  65493. attribs.push("world1");
  65494. attribs.push("world2");
  65495. attribs.push("world3");
  65496. }
  65497. // Get correct effect
  65498. var join = defines.join("\n");
  65499. if (this._cachedDefines !== join) {
  65500. this._cachedDefines = join;
  65501. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  65502. }
  65503. return this._effect.isReady();
  65504. };
  65505. /**
  65506. * Gets the current underlying G Buffer.
  65507. * @returns the buffer
  65508. */
  65509. GeometryBufferRenderer.prototype.getGBuffer = function () {
  65510. return this._multiRenderTarget;
  65511. };
  65512. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  65513. /**
  65514. * Gets the number of samples used to render the buffer (anti aliasing).
  65515. */
  65516. get: function () {
  65517. return this._multiRenderTarget.samples;
  65518. },
  65519. /**
  65520. * Sets the number of samples used to render the buffer (anti aliasing).
  65521. */
  65522. set: function (value) {
  65523. this._multiRenderTarget.samples = value;
  65524. },
  65525. enumerable: true,
  65526. configurable: true
  65527. });
  65528. /**
  65529. * Disposes the renderer and frees up associated resources.
  65530. */
  65531. GeometryBufferRenderer.prototype.dispose = function () {
  65532. this.getGBuffer().dispose();
  65533. };
  65534. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  65535. var _this = this;
  65536. var engine = this._scene.getEngine();
  65537. var count = this._enablePosition ? 3 : 2;
  65538. 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 });
  65539. if (!this.isSupported) {
  65540. return;
  65541. }
  65542. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65543. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65544. this._multiRenderTarget.refreshRate = 1;
  65545. this._multiRenderTarget.renderParticles = false;
  65546. this._multiRenderTarget.renderList = null;
  65547. // set default depth value to 1.0 (far away)
  65548. this._multiRenderTarget.onClearObservable.add(function (engine) {
  65549. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  65550. });
  65551. // Custom render function
  65552. var renderSubMesh = function (subMesh) {
  65553. var mesh = subMesh.getRenderingMesh();
  65554. var scene = _this._scene;
  65555. var engine = scene.getEngine();
  65556. var material = subMesh.getMaterial();
  65557. if (!material) {
  65558. return;
  65559. }
  65560. // Culling
  65561. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  65562. // Managing instances
  65563. var batch = mesh._getInstancesRenderList(subMesh._id);
  65564. if (batch.mustReturn) {
  65565. return;
  65566. }
  65567. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65568. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  65569. engine.enableEffect(_this._effect);
  65570. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  65571. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65572. _this._effect.setMatrix("view", scene.getViewMatrix());
  65573. // Alpha test
  65574. if (material && material.needAlphaTesting()) {
  65575. var alphaTexture = material.getAlphaTestTexture();
  65576. if (alphaTexture) {
  65577. _this._effect.setTexture("diffuseSampler", alphaTexture);
  65578. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65579. }
  65580. }
  65581. // Bones
  65582. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65583. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65584. }
  65585. // Draw
  65586. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65587. }
  65588. };
  65589. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65590. var index;
  65591. if (depthOnlySubMeshes.length) {
  65592. engine.setColorWrite(false);
  65593. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65594. renderSubMesh(depthOnlySubMeshes.data[index]);
  65595. }
  65596. engine.setColorWrite(true);
  65597. }
  65598. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65599. renderSubMesh(opaqueSubMeshes.data[index]);
  65600. }
  65601. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65602. renderSubMesh(alphaTestSubMeshes.data[index]);
  65603. }
  65604. };
  65605. };
  65606. return GeometryBufferRenderer;
  65607. }());
  65608. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  65609. })(BABYLON || (BABYLON = {}));
  65610. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  65611. var BABYLON;
  65612. (function (BABYLON) {
  65613. var RefractionPostProcess = /** @class */ (function (_super) {
  65614. __extends(RefractionPostProcess, _super);
  65615. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  65616. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  65617. _this.color = color;
  65618. _this.depth = depth;
  65619. _this.colorLevel = colorLevel;
  65620. _this.onActivateObservable.add(function (cam) {
  65621. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  65622. });
  65623. _this.onApplyObservable.add(function (effect) {
  65624. effect.setColor3("baseColor", _this.color);
  65625. effect.setFloat("depth", _this.depth);
  65626. effect.setFloat("colorLevel", _this.colorLevel);
  65627. effect.setTexture("refractionSampler", _this._refRexture);
  65628. });
  65629. return _this;
  65630. }
  65631. // Methods
  65632. RefractionPostProcess.prototype.dispose = function (camera) {
  65633. if (this._refRexture) {
  65634. this._refRexture.dispose();
  65635. }
  65636. _super.prototype.dispose.call(this, camera);
  65637. };
  65638. return RefractionPostProcess;
  65639. }(BABYLON.PostProcess));
  65640. BABYLON.RefractionPostProcess = RefractionPostProcess;
  65641. })(BABYLON || (BABYLON = {}));
  65642. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  65643. var BABYLON;
  65644. (function (BABYLON) {
  65645. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  65646. __extends(BlackAndWhitePostProcess, _super);
  65647. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  65648. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  65649. _this.degree = 1;
  65650. _this.onApplyObservable.add(function (effect) {
  65651. effect.setFloat("degree", _this.degree);
  65652. });
  65653. return _this;
  65654. }
  65655. return BlackAndWhitePostProcess;
  65656. }(BABYLON.PostProcess));
  65657. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  65658. })(BABYLON || (BABYLON = {}));
  65659. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  65660. var BABYLON;
  65661. (function (BABYLON) {
  65662. var ConvolutionPostProcess = /** @class */ (function (_super) {
  65663. __extends(ConvolutionPostProcess, _super);
  65664. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  65665. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  65666. _this.kernel = kernel;
  65667. _this.onApply = function (effect) {
  65668. effect.setFloat2("screenSize", _this.width, _this.height);
  65669. effect.setArray("kernel", _this.kernel);
  65670. };
  65671. return _this;
  65672. }
  65673. // Statics
  65674. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  65675. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  65676. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  65677. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  65678. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  65679. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  65680. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  65681. return ConvolutionPostProcess;
  65682. }(BABYLON.PostProcess));
  65683. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  65684. })(BABYLON || (BABYLON = {}));
  65685. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  65686. var BABYLON;
  65687. (function (BABYLON) {
  65688. var FilterPostProcess = /** @class */ (function (_super) {
  65689. __extends(FilterPostProcess, _super);
  65690. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  65691. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  65692. _this.kernelMatrix = kernelMatrix;
  65693. _this.onApply = function (effect) {
  65694. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  65695. };
  65696. return _this;
  65697. }
  65698. return FilterPostProcess;
  65699. }(BABYLON.PostProcess));
  65700. BABYLON.FilterPostProcess = FilterPostProcess;
  65701. })(BABYLON || (BABYLON = {}));
  65702. //# sourceMappingURL=babylon.filterPostProcess.js.map
  65703. var BABYLON;
  65704. (function (BABYLON) {
  65705. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  65706. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  65707. __extends(VolumetricLightScatteringPostProcess, _super);
  65708. /**
  65709. * @constructor
  65710. * @param {string} name - The post-process name
  65711. * @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)
  65712. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  65713. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  65714. * @param {number} samples - The post-process quality, default 100
  65715. * @param {number} samplingMode - The post-process filtering mode
  65716. * @param {BABYLON.Engine} engine - The babylon engine
  65717. * @param {boolean} reusable - If the post-process is reusable
  65718. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  65719. */
  65720. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  65721. if (samples === void 0) { samples = 100; }
  65722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65723. 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;
  65724. _this._screenCoordinates = BABYLON.Vector2.Zero();
  65725. /**
  65726. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  65727. * @type {Vector3}
  65728. */
  65729. _this.customMeshPosition = BABYLON.Vector3.Zero();
  65730. /**
  65731. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  65732. * @type {boolean}
  65733. */
  65734. _this.useCustomMeshPosition = false;
  65735. /**
  65736. * If the post-process should inverse the light scattering direction
  65737. * @type {boolean}
  65738. */
  65739. _this.invert = true;
  65740. /**
  65741. * Array containing the excluded meshes not rendered in the internal pass
  65742. */
  65743. _this.excludedMeshes = new Array();
  65744. /**
  65745. * Controls the overall intensity of the post-process
  65746. * @type {number}
  65747. */
  65748. _this.exposure = 0.3;
  65749. /**
  65750. * Dissipates each sample's contribution in range [0, 1]
  65751. * @type {number}
  65752. */
  65753. _this.decay = 0.96815;
  65754. /**
  65755. * Controls the overall intensity of each sample
  65756. * @type {number}
  65757. */
  65758. _this.weight = 0.58767;
  65759. /**
  65760. * Controls the density of each sample
  65761. * @type {number}
  65762. */
  65763. _this.density = 0.926;
  65764. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  65765. engine = scene.getEngine();
  65766. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  65767. // Configure mesh
  65768. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  65769. // Configure
  65770. _this._createPass(scene, ratio.passRatio || ratio);
  65771. _this.onActivate = function (camera) {
  65772. if (!_this.isSupported) {
  65773. _this.dispose(camera);
  65774. }
  65775. _this.onActivate = null;
  65776. };
  65777. _this.onApplyObservable.add(function (effect) {
  65778. _this._updateMeshScreenCoordinates(scene);
  65779. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  65780. effect.setFloat("exposure", _this.exposure);
  65781. effect.setFloat("decay", _this.decay);
  65782. effect.setFloat("weight", _this.weight);
  65783. effect.setFloat("density", _this.density);
  65784. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  65785. });
  65786. return _this;
  65787. }
  65788. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  65789. get: function () {
  65790. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65791. return false;
  65792. },
  65793. set: function (useDiffuseColor) {
  65794. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65795. },
  65796. enumerable: true,
  65797. configurable: true
  65798. });
  65799. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  65800. return "VolumetricLightScatteringPostProcess";
  65801. };
  65802. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  65803. var mesh = subMesh.getMesh();
  65804. // Render this.mesh as default
  65805. if (mesh === this.mesh && mesh.material) {
  65806. return mesh.material.isReady(mesh);
  65807. }
  65808. var defines = [];
  65809. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65810. var material = subMesh.getMaterial();
  65811. // Alpha test
  65812. if (material) {
  65813. if (material.needAlphaTesting()) {
  65814. defines.push("#define ALPHATEST");
  65815. }
  65816. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65817. attribs.push(BABYLON.VertexBuffer.UVKind);
  65818. defines.push("#define UV1");
  65819. }
  65820. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65821. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65822. defines.push("#define UV2");
  65823. }
  65824. }
  65825. // Bones
  65826. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65827. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65828. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65829. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65830. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  65831. }
  65832. else {
  65833. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65834. }
  65835. // Instances
  65836. if (useInstances) {
  65837. defines.push("#define INSTANCES");
  65838. attribs.push("world0");
  65839. attribs.push("world1");
  65840. attribs.push("world2");
  65841. attribs.push("world3");
  65842. }
  65843. // Get correct effect
  65844. var join = defines.join("\n");
  65845. if (this._cachedDefines !== join) {
  65846. this._cachedDefines = join;
  65847. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  65848. }
  65849. return this._volumetricLightScatteringPass.isReady();
  65850. };
  65851. /**
  65852. * Sets the new light position for light scattering effect
  65853. * @param {BABYLON.Vector3} The new custom light position
  65854. */
  65855. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  65856. this.customMeshPosition = position;
  65857. };
  65858. /**
  65859. * Returns the light position for light scattering effect
  65860. * @return {BABYLON.Vector3} The custom light position
  65861. */
  65862. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  65863. return this.customMeshPosition;
  65864. };
  65865. /**
  65866. * Disposes the internal assets and detaches the post-process from the camera
  65867. */
  65868. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  65869. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  65870. if (rttIndex !== -1) {
  65871. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  65872. }
  65873. this._volumetricLightScatteringRTT.dispose();
  65874. _super.prototype.dispose.call(this, camera);
  65875. };
  65876. /**
  65877. * Returns the render target texture used by the post-process
  65878. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  65879. */
  65880. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  65881. return this._volumetricLightScatteringRTT;
  65882. };
  65883. // Private methods
  65884. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  65885. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  65886. return true;
  65887. }
  65888. return false;
  65889. };
  65890. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  65891. var _this = this;
  65892. var engine = scene.getEngine();
  65893. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65894. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65895. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65896. this._volumetricLightScatteringRTT.renderList = null;
  65897. this._volumetricLightScatteringRTT.renderParticles = false;
  65898. var camera = this.getCamera();
  65899. if (camera) {
  65900. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65901. }
  65902. else {
  65903. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65904. }
  65905. // Custom render function for submeshes
  65906. var renderSubMesh = function (subMesh) {
  65907. var mesh = subMesh.getRenderingMesh();
  65908. if (_this._meshExcluded(mesh)) {
  65909. return;
  65910. }
  65911. var material = subMesh.getMaterial();
  65912. if (!material) {
  65913. return;
  65914. }
  65915. var scene = mesh.getScene();
  65916. var engine = scene.getEngine();
  65917. // Culling
  65918. engine.setState(material.backFaceCulling);
  65919. // Managing instances
  65920. var batch = mesh._getInstancesRenderList(subMesh._id);
  65921. if (batch.mustReturn) {
  65922. return;
  65923. }
  65924. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65925. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  65926. var effect = _this._volumetricLightScatteringPass;
  65927. if (mesh === _this.mesh) {
  65928. if (subMesh.effect) {
  65929. effect = subMesh.effect;
  65930. }
  65931. else {
  65932. effect = material.getEffect();
  65933. }
  65934. }
  65935. engine.enableEffect(effect);
  65936. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  65937. if (mesh === _this.mesh) {
  65938. material.bind(mesh.getWorldMatrix(), mesh);
  65939. }
  65940. else {
  65941. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  65942. // Alpha test
  65943. if (material && material.needAlphaTesting()) {
  65944. var alphaTexture = material.getAlphaTestTexture();
  65945. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  65946. if (alphaTexture) {
  65947. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65948. }
  65949. }
  65950. // Bones
  65951. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65952. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65953. }
  65954. }
  65955. // Draw
  65956. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  65957. }
  65958. };
  65959. // Render target texture callbacks
  65960. var savedSceneClearColor;
  65961. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  65962. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  65963. savedSceneClearColor = scene.clearColor;
  65964. scene.clearColor = sceneClearColor;
  65965. });
  65966. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  65967. scene.clearColor = savedSceneClearColor;
  65968. });
  65969. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65970. var engine = scene.getEngine();
  65971. var index;
  65972. if (depthOnlySubMeshes.length) {
  65973. engine.setColorWrite(false);
  65974. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65975. renderSubMesh(depthOnlySubMeshes.data[index]);
  65976. }
  65977. engine.setColorWrite(true);
  65978. }
  65979. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65980. renderSubMesh(opaqueSubMeshes.data[index]);
  65981. }
  65982. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65983. renderSubMesh(alphaTestSubMeshes.data[index]);
  65984. }
  65985. if (transparentSubMeshes.length) {
  65986. // Sort sub meshes
  65987. for (index = 0; index < transparentSubMeshes.length; index++) {
  65988. var submesh = transparentSubMeshes.data[index];
  65989. var boundingInfo = submesh.getBoundingInfo();
  65990. if (boundingInfo && scene.activeCamera) {
  65991. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  65992. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  65993. }
  65994. }
  65995. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  65996. sortedArray.sort(function (a, b) {
  65997. // Alpha index first
  65998. if (a._alphaIndex > b._alphaIndex) {
  65999. return 1;
  66000. }
  66001. if (a._alphaIndex < b._alphaIndex) {
  66002. return -1;
  66003. }
  66004. // Then distance to camera
  66005. if (a._distanceToCamera < b._distanceToCamera) {
  66006. return 1;
  66007. }
  66008. if (a._distanceToCamera > b._distanceToCamera) {
  66009. return -1;
  66010. }
  66011. return 0;
  66012. });
  66013. // Render sub meshes
  66014. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  66015. for (index = 0; index < sortedArray.length; index++) {
  66016. renderSubMesh(sortedArray[index]);
  66017. }
  66018. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66019. }
  66020. };
  66021. };
  66022. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  66023. var transform = scene.getTransformMatrix();
  66024. var meshPosition;
  66025. if (this.useCustomMeshPosition) {
  66026. meshPosition = this.customMeshPosition;
  66027. }
  66028. else if (this.attachedNode) {
  66029. meshPosition = this.attachedNode.position;
  66030. }
  66031. else {
  66032. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  66033. }
  66034. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  66035. this._screenCoordinates.x = pos.x / this._viewPort.width;
  66036. this._screenCoordinates.y = pos.y / this._viewPort.height;
  66037. if (this.invert)
  66038. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  66039. };
  66040. // Static methods
  66041. /**
  66042. * Creates a default mesh for the Volumeric Light Scattering post-process
  66043. * @param {string} The mesh name
  66044. * @param {BABYLON.Scene} The scene where to create the mesh
  66045. * @return {BABYLON.Mesh} the default mesh
  66046. */
  66047. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  66048. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  66049. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  66050. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  66051. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  66052. mesh.material = material;
  66053. return mesh;
  66054. };
  66055. __decorate([
  66056. BABYLON.serializeAsVector3()
  66057. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  66058. __decorate([
  66059. BABYLON.serialize()
  66060. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  66061. __decorate([
  66062. BABYLON.serialize()
  66063. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  66064. __decorate([
  66065. BABYLON.serializeAsMeshReference()
  66066. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  66067. __decorate([
  66068. BABYLON.serialize()
  66069. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  66070. __decorate([
  66071. BABYLON.serialize()
  66072. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  66073. __decorate([
  66074. BABYLON.serialize()
  66075. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  66076. __decorate([
  66077. BABYLON.serialize()
  66078. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  66079. __decorate([
  66080. BABYLON.serialize()
  66081. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  66082. return VolumetricLightScatteringPostProcess;
  66083. }(BABYLON.PostProcess));
  66084. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  66085. })(BABYLON || (BABYLON = {}));
  66086. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  66087. //
  66088. // This post-process allows the modification of rendered colors by using
  66089. // a 'look-up table' (LUT). This effect is also called Color Grading.
  66090. //
  66091. // The object needs to be provided an url to a texture containing the color
  66092. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  66093. // Use an image editing software to tweak the LUT to match your needs.
  66094. //
  66095. // For an example of a color LUT, see here:
  66096. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  66097. // For explanations on color grading, see here:
  66098. // http://udn.epicgames.com/Three/ColorGrading.html
  66099. //
  66100. var BABYLON;
  66101. (function (BABYLON) {
  66102. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  66103. __extends(ColorCorrectionPostProcess, _super);
  66104. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  66105. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  66106. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66107. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  66108. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66109. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66110. _this.onApply = function (effect) {
  66111. effect.setTexture("colorTable", _this._colorTableTexture);
  66112. };
  66113. return _this;
  66114. }
  66115. return ColorCorrectionPostProcess;
  66116. }(BABYLON.PostProcess));
  66117. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  66118. })(BABYLON || (BABYLON = {}));
  66119. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  66120. var BABYLON;
  66121. (function (BABYLON) {
  66122. var TonemappingOperator;
  66123. (function (TonemappingOperator) {
  66124. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  66125. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  66126. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  66127. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  66128. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  66129. ;
  66130. var TonemapPostProcess = /** @class */ (function (_super) {
  66131. __extends(TonemapPostProcess, _super);
  66132. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  66133. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66134. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66135. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  66136. _this._operator = _operator;
  66137. _this.exposureAdjustment = exposureAdjustment;
  66138. var defines = "#define ";
  66139. if (_this._operator === TonemappingOperator.Hable)
  66140. defines += "HABLE_TONEMAPPING";
  66141. else if (_this._operator === TonemappingOperator.Reinhard)
  66142. defines += "REINHARD_TONEMAPPING";
  66143. else if (_this._operator === TonemappingOperator.HejiDawson)
  66144. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  66145. else if (_this._operator === TonemappingOperator.Photographic)
  66146. defines += "PHOTOGRAPHIC_TONEMAPPING";
  66147. //sadly a second call to create the effect.
  66148. _this.updateEffect(defines);
  66149. _this.onApply = function (effect) {
  66150. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  66151. };
  66152. return _this;
  66153. }
  66154. return TonemapPostProcess;
  66155. }(BABYLON.PostProcess));
  66156. BABYLON.TonemapPostProcess = TonemapPostProcess;
  66157. })(BABYLON || (BABYLON = {}));
  66158. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  66159. var BABYLON;
  66160. (function (BABYLON) {
  66161. var DisplayPassPostProcess = /** @class */ (function (_super) {
  66162. __extends(DisplayPassPostProcess, _super);
  66163. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  66164. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  66165. }
  66166. return DisplayPassPostProcess;
  66167. }(BABYLON.PostProcess));
  66168. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  66169. })(BABYLON || (BABYLON = {}));
  66170. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  66171. var BABYLON;
  66172. (function (BABYLON) {
  66173. var HighlightsPostProcess = /** @class */ (function (_super) {
  66174. __extends(HighlightsPostProcess, _super);
  66175. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  66176. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66177. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  66178. }
  66179. return HighlightsPostProcess;
  66180. }(BABYLON.PostProcess));
  66181. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  66182. })(BABYLON || (BABYLON = {}));
  66183. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  66184. var BABYLON;
  66185. (function (BABYLON) {
  66186. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  66187. __extends(ImageProcessingPostProcess, _super);
  66188. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  66189. if (camera === void 0) { camera = null; }
  66190. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66191. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  66192. _this._fromLinearSpace = true;
  66193. /**
  66194. * Defines cache preventing GC.
  66195. */
  66196. _this._defines = {
  66197. IMAGEPROCESSING: false,
  66198. VIGNETTE: false,
  66199. VIGNETTEBLENDMODEMULTIPLY: false,
  66200. VIGNETTEBLENDMODEOPAQUE: false,
  66201. TONEMAPPING: false,
  66202. CONTRAST: false,
  66203. COLORCURVES: false,
  66204. COLORGRADING: false,
  66205. COLORGRADING3D: false,
  66206. FROMLINEARSPACE: false,
  66207. SAMPLER3DGREENDEPTH: false,
  66208. SAMPLER3DBGRMAP: false,
  66209. IMAGEPROCESSINGPOSTPROCESS: false,
  66210. EXPOSURE: false,
  66211. };
  66212. // Setup the configuration as forced by the constructor. This would then not force the
  66213. // scene materials output in linear space and let untouched the default forward pass.
  66214. if (imageProcessingConfiguration) {
  66215. imageProcessingConfiguration.applyByPostProcess = true;
  66216. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  66217. // This will cause the shader to be compiled
  66218. _this.fromLinearSpace = false;
  66219. }
  66220. else {
  66221. _this._attachImageProcessingConfiguration(null, true);
  66222. _this.imageProcessingConfiguration.applyByPostProcess = true;
  66223. }
  66224. _this.onApply = function (effect) {
  66225. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  66226. };
  66227. return _this;
  66228. }
  66229. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  66230. /**
  66231. * Gets the image processing configuration used either in this material.
  66232. */
  66233. get: function () {
  66234. return this._imageProcessingConfiguration;
  66235. },
  66236. /**
  66237. * Sets the Default image processing configuration used either in the this material.
  66238. *
  66239. * If sets to null, the scene one is in use.
  66240. */
  66241. set: function (value) {
  66242. this._attachImageProcessingConfiguration(value);
  66243. },
  66244. enumerable: true,
  66245. configurable: true
  66246. });
  66247. /**
  66248. * Attaches a new image processing configuration to the PBR Material.
  66249. * @param configuration
  66250. */
  66251. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  66252. var _this = this;
  66253. if (doNotBuild === void 0) { doNotBuild = false; }
  66254. if (configuration === this._imageProcessingConfiguration) {
  66255. return;
  66256. }
  66257. // Detaches observer.
  66258. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  66259. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  66260. }
  66261. // Pick the scene configuration if needed.
  66262. if (!configuration) {
  66263. var scene = null;
  66264. var engine = this.getEngine();
  66265. var camera = this.getCamera();
  66266. if (camera) {
  66267. scene = camera.getScene();
  66268. }
  66269. else if (engine && engine.scenes) {
  66270. var scenes = engine.scenes;
  66271. scene = scenes[scenes.length - 1];
  66272. }
  66273. else {
  66274. scene = BABYLON.Engine.LastCreatedScene;
  66275. }
  66276. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  66277. }
  66278. else {
  66279. this._imageProcessingConfiguration = configuration;
  66280. }
  66281. // Attaches observer.
  66282. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  66283. _this._updateParameters();
  66284. });
  66285. // Ensure the effect will be rebuilt.
  66286. if (!doNotBuild) {
  66287. this._updateParameters();
  66288. }
  66289. };
  66290. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  66291. /**
  66292. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  66293. */
  66294. get: function () {
  66295. return this.imageProcessingConfiguration.colorCurves;
  66296. },
  66297. /**
  66298. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  66299. */
  66300. set: function (value) {
  66301. this.imageProcessingConfiguration.colorCurves = value;
  66302. },
  66303. enumerable: true,
  66304. configurable: true
  66305. });
  66306. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  66307. /**
  66308. * Gets wether the color curves effect is enabled.
  66309. */
  66310. get: function () {
  66311. return this.imageProcessingConfiguration.colorCurvesEnabled;
  66312. },
  66313. /**
  66314. * Sets wether the color curves effect is enabled.
  66315. */
  66316. set: function (value) {
  66317. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  66318. },
  66319. enumerable: true,
  66320. configurable: true
  66321. });
  66322. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  66323. /**
  66324. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  66325. */
  66326. get: function () {
  66327. return this.imageProcessingConfiguration.colorGradingTexture;
  66328. },
  66329. /**
  66330. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  66331. */
  66332. set: function (value) {
  66333. this.imageProcessingConfiguration.colorGradingTexture = value;
  66334. },
  66335. enumerable: true,
  66336. configurable: true
  66337. });
  66338. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  66339. /**
  66340. * Gets wether the color grading effect is enabled.
  66341. */
  66342. get: function () {
  66343. return this.imageProcessingConfiguration.colorGradingEnabled;
  66344. },
  66345. /**
  66346. * Gets wether the color grading effect is enabled.
  66347. */
  66348. set: function (value) {
  66349. this.imageProcessingConfiguration.colorGradingEnabled = value;
  66350. },
  66351. enumerable: true,
  66352. configurable: true
  66353. });
  66354. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  66355. /**
  66356. * Gets exposure used in the effect.
  66357. */
  66358. get: function () {
  66359. return this.imageProcessingConfiguration.exposure;
  66360. },
  66361. /**
  66362. * Sets exposure used in the effect.
  66363. */
  66364. set: function (value) {
  66365. this.imageProcessingConfiguration.exposure = value;
  66366. },
  66367. enumerable: true,
  66368. configurable: true
  66369. });
  66370. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  66371. /**
  66372. * Gets wether tonemapping is enabled or not.
  66373. */
  66374. get: function () {
  66375. return this._imageProcessingConfiguration.toneMappingEnabled;
  66376. },
  66377. /**
  66378. * Sets wether tonemapping is enabled or not
  66379. */
  66380. set: function (value) {
  66381. this._imageProcessingConfiguration.toneMappingEnabled = value;
  66382. },
  66383. enumerable: true,
  66384. configurable: true
  66385. });
  66386. ;
  66387. ;
  66388. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  66389. /**
  66390. * Gets contrast used in the effect.
  66391. */
  66392. get: function () {
  66393. return this.imageProcessingConfiguration.contrast;
  66394. },
  66395. /**
  66396. * Sets contrast used in the effect.
  66397. */
  66398. set: function (value) {
  66399. this.imageProcessingConfiguration.contrast = value;
  66400. },
  66401. enumerable: true,
  66402. configurable: true
  66403. });
  66404. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  66405. /**
  66406. * Gets Vignette stretch size.
  66407. */
  66408. get: function () {
  66409. return this.imageProcessingConfiguration.vignetteStretch;
  66410. },
  66411. /**
  66412. * Sets Vignette stretch size.
  66413. */
  66414. set: function (value) {
  66415. this.imageProcessingConfiguration.vignetteStretch = value;
  66416. },
  66417. enumerable: true,
  66418. configurable: true
  66419. });
  66420. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  66421. /**
  66422. * Gets Vignette centre X Offset.
  66423. */
  66424. get: function () {
  66425. return this.imageProcessingConfiguration.vignetteCentreX;
  66426. },
  66427. /**
  66428. * Sets Vignette centre X Offset.
  66429. */
  66430. set: function (value) {
  66431. this.imageProcessingConfiguration.vignetteCentreX = value;
  66432. },
  66433. enumerable: true,
  66434. configurable: true
  66435. });
  66436. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  66437. /**
  66438. * Gets Vignette centre Y Offset.
  66439. */
  66440. get: function () {
  66441. return this.imageProcessingConfiguration.vignetteCentreY;
  66442. },
  66443. /**
  66444. * Sets Vignette centre Y Offset.
  66445. */
  66446. set: function (value) {
  66447. this.imageProcessingConfiguration.vignetteCentreY = value;
  66448. },
  66449. enumerable: true,
  66450. configurable: true
  66451. });
  66452. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  66453. /**
  66454. * Gets Vignette weight or intensity of the vignette effect.
  66455. */
  66456. get: function () {
  66457. return this.imageProcessingConfiguration.vignetteWeight;
  66458. },
  66459. /**
  66460. * Sets Vignette weight or intensity of the vignette effect.
  66461. */
  66462. set: function (value) {
  66463. this.imageProcessingConfiguration.vignetteWeight = value;
  66464. },
  66465. enumerable: true,
  66466. configurable: true
  66467. });
  66468. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  66469. /**
  66470. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  66471. * if vignetteEnabled is set to true.
  66472. */
  66473. get: function () {
  66474. return this.imageProcessingConfiguration.vignetteColor;
  66475. },
  66476. /**
  66477. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  66478. * if vignetteEnabled is set to true.
  66479. */
  66480. set: function (value) {
  66481. this.imageProcessingConfiguration.vignetteColor = value;
  66482. },
  66483. enumerable: true,
  66484. configurable: true
  66485. });
  66486. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  66487. /**
  66488. * Gets Camera field of view used by the Vignette effect.
  66489. */
  66490. get: function () {
  66491. return this.imageProcessingConfiguration.vignetteCameraFov;
  66492. },
  66493. /**
  66494. * Sets Camera field of view used by the Vignette effect.
  66495. */
  66496. set: function (value) {
  66497. this.imageProcessingConfiguration.vignetteCameraFov = value;
  66498. },
  66499. enumerable: true,
  66500. configurable: true
  66501. });
  66502. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  66503. /**
  66504. * Gets the vignette blend mode allowing different kind of effect.
  66505. */
  66506. get: function () {
  66507. return this.imageProcessingConfiguration.vignetteBlendMode;
  66508. },
  66509. /**
  66510. * Sets the vignette blend mode allowing different kind of effect.
  66511. */
  66512. set: function (value) {
  66513. this.imageProcessingConfiguration.vignetteBlendMode = value;
  66514. },
  66515. enumerable: true,
  66516. configurable: true
  66517. });
  66518. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  66519. /**
  66520. * Gets wether the vignette effect is enabled.
  66521. */
  66522. get: function () {
  66523. return this.imageProcessingConfiguration.vignetteEnabled;
  66524. },
  66525. /**
  66526. * Sets wether the vignette effect is enabled.
  66527. */
  66528. set: function (value) {
  66529. this.imageProcessingConfiguration.vignetteEnabled = value;
  66530. },
  66531. enumerable: true,
  66532. configurable: true
  66533. });
  66534. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  66535. /**
  66536. * Gets wether the input of the processing is in Gamma or Linear Space.
  66537. */
  66538. get: function () {
  66539. return this._fromLinearSpace;
  66540. },
  66541. /**
  66542. * Sets wether the input of the processing is in Gamma or Linear Space.
  66543. */
  66544. set: function (value) {
  66545. if (this._fromLinearSpace === value) {
  66546. return;
  66547. }
  66548. this._fromLinearSpace = value;
  66549. this._updateParameters();
  66550. },
  66551. enumerable: true,
  66552. configurable: true
  66553. });
  66554. ImageProcessingPostProcess.prototype.getClassName = function () {
  66555. return "ImageProcessingPostProcess";
  66556. };
  66557. ImageProcessingPostProcess.prototype._updateParameters = function () {
  66558. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  66559. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  66560. var defines = "";
  66561. for (var define in this._defines) {
  66562. if (this._defines[define]) {
  66563. defines += "#define " + define + ";\r\n";
  66564. }
  66565. }
  66566. var samplers = ["textureSampler"];
  66567. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  66568. var uniforms = ["scale"];
  66569. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  66570. this.updateEffect(defines, uniforms, samplers);
  66571. };
  66572. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  66573. _super.prototype.dispose.call(this, camera);
  66574. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  66575. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  66576. }
  66577. this.imageProcessingConfiguration.applyByPostProcess = false;
  66578. };
  66579. __decorate([
  66580. BABYLON.serialize()
  66581. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  66582. return ImageProcessingPostProcess;
  66583. }(BABYLON.PostProcess));
  66584. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  66585. })(BABYLON || (BABYLON = {}));
  66586. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  66587. var BABYLON;
  66588. (function (BABYLON) {
  66589. /**
  66590. * The Blur Post Process which blurs an image based on a kernel and direction.
  66591. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  66592. */
  66593. var BlurPostProcess = /** @class */ (function (_super) {
  66594. __extends(BlurPostProcess, _super);
  66595. /**
  66596. * Creates a new instance of @see BlurPostProcess
  66597. * @param name The name of the effect.
  66598. * @param direction The direction in which to blur the image.
  66599. * @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.
  66600. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  66601. * @param camera The camera to apply the render pass to.
  66602. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66603. * @param engine The engine which the post process will be applied. (default: current engine)
  66604. * @param reusable If the post process can be reused on the same frame. (default: false)
  66605. * @param textureType Type of textures used when performing the post process. (default: 0)
  66606. */
  66607. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  66608. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66609. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66610. 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;
  66611. _this.direction = direction;
  66612. _this._packedFloat = false;
  66613. _this._staticDefines = "";
  66614. _this.onApplyObservable.add(function (effect) {
  66615. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  66616. });
  66617. _this.kernel = kernel;
  66618. return _this;
  66619. }
  66620. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  66621. /**
  66622. * Gets the length in pixels of the blur sample region
  66623. */
  66624. get: function () {
  66625. return this._idealKernel;
  66626. },
  66627. /**
  66628. * Sets the length in pixels of the blur sample region
  66629. */
  66630. set: function (v) {
  66631. if (this._idealKernel === v) {
  66632. return;
  66633. }
  66634. v = Math.max(v, 1);
  66635. this._idealKernel = v;
  66636. this._kernel = this._nearestBestKernel(v);
  66637. this._updateParameters();
  66638. },
  66639. enumerable: true,
  66640. configurable: true
  66641. });
  66642. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  66643. /**
  66644. * Gets wether or not the blur is unpacking/repacking floats
  66645. */
  66646. get: function () {
  66647. return this._packedFloat;
  66648. },
  66649. /**
  66650. * Sets wether or not the blur needs to unpack/repack floats
  66651. */
  66652. set: function (v) {
  66653. if (this._packedFloat === v) {
  66654. return;
  66655. }
  66656. this._packedFloat = v;
  66657. this._updateParameters();
  66658. },
  66659. enumerable: true,
  66660. configurable: true
  66661. });
  66662. BlurPostProcess.prototype._updateParameters = function () {
  66663. // Generate sampling offsets and weights
  66664. var N = this._kernel;
  66665. var centerIndex = (N - 1) / 2;
  66666. // Generate Gaussian sampling weights over kernel
  66667. var offsets = [];
  66668. var weights = [];
  66669. var totalWeight = 0;
  66670. for (var i = 0; i < N; i++) {
  66671. var u = i / (N - 1);
  66672. var w = this._gaussianWeight(u * 2.0 - 1);
  66673. offsets[i] = (i - centerIndex);
  66674. weights[i] = w;
  66675. totalWeight += w;
  66676. }
  66677. // Normalize weights
  66678. for (var i = 0; i < weights.length; i++) {
  66679. weights[i] /= totalWeight;
  66680. }
  66681. // Optimize: combine samples to take advantage of hardware linear sampling
  66682. // Walk from left to center, combining pairs (symmetrically)
  66683. var linearSamplingWeights = [];
  66684. var linearSamplingOffsets = [];
  66685. var linearSamplingMap = [];
  66686. for (var i = 0; i <= centerIndex; i += 2) {
  66687. var j = Math.min(i + 1, Math.floor(centerIndex));
  66688. var singleCenterSample = i === j;
  66689. if (singleCenterSample) {
  66690. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66691. }
  66692. else {
  66693. var sharedCell = j === centerIndex;
  66694. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  66695. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  66696. if (offsetLinear === 0) {
  66697. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66698. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  66699. }
  66700. else {
  66701. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  66702. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  66703. }
  66704. }
  66705. }
  66706. for (var i = 0; i < linearSamplingMap.length; i++) {
  66707. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  66708. linearSamplingWeights[i] = linearSamplingMap[i].w;
  66709. }
  66710. // Replace with optimized
  66711. offsets = linearSamplingOffsets;
  66712. weights = linearSamplingWeights;
  66713. // Generate shaders
  66714. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  66715. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  66716. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  66717. var defines = "";
  66718. defines += this._staticDefines;
  66719. for (var i = 0; i < varyingCount; i++) {
  66720. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  66721. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  66722. }
  66723. var depCount = 0;
  66724. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  66725. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  66726. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  66727. depCount++;
  66728. }
  66729. if (this.packedFloat) {
  66730. defines += "#define PACKEDFLOAT 1";
  66731. }
  66732. this.updateEffect(defines, null, null, {
  66733. varyingCount: varyingCount,
  66734. depCount: depCount
  66735. });
  66736. };
  66737. /**
  66738. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  66739. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  66740. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  66741. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  66742. * The gaps between physical kernels are compensated for in the weighting of the samples
  66743. * @param idealKernel Ideal blur kernel.
  66744. * @return Nearest best kernel.
  66745. */
  66746. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  66747. var v = Math.round(idealKernel);
  66748. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  66749. var k = _a[_i];
  66750. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  66751. return Math.max(k, 3);
  66752. }
  66753. }
  66754. return Math.max(v, 3);
  66755. };
  66756. /**
  66757. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  66758. * @param x The point on the Gaussian distribution to sample.
  66759. * @return the value of the Gaussian function at x.
  66760. */
  66761. BlurPostProcess.prototype._gaussianWeight = function (x) {
  66762. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  66763. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  66764. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  66765. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  66766. // truncated at around 1.3% of peak strength.
  66767. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  66768. var sigma = (1 / 3);
  66769. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  66770. var exponent = -((x * x) / (2.0 * sigma * sigma));
  66771. var weight = (1.0 / denominator) * Math.exp(exponent);
  66772. return weight;
  66773. };
  66774. /**
  66775. * Generates a string that can be used as a floating point number in GLSL.
  66776. * @param x Value to print.
  66777. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  66778. * @return GLSL float string.
  66779. */
  66780. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  66781. if (decimalFigures === void 0) { decimalFigures = 8; }
  66782. return x.toFixed(decimalFigures).replace(/0+$/, '');
  66783. };
  66784. return BlurPostProcess;
  66785. }(BABYLON.PostProcess));
  66786. BABYLON.BlurPostProcess = BlurPostProcess;
  66787. })(BABYLON || (BABYLON = {}));
  66788. //# sourceMappingURL=babylon.blurPostProcess.js.map
  66789. var BABYLON;
  66790. (function (BABYLON) {
  66791. /**
  66792. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  66793. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  66794. * based on samples that have a large difference in distance than the center pixel.
  66795. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  66796. */
  66797. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  66798. __extends(DepthOfFieldBlurPostProcess, _super);
  66799. /**
  66800. * Creates a new instance of @see CircleOfConfusionPostProcess
  66801. * @param name The name of the effect.
  66802. * @param scene The scene the effect belongs to.
  66803. * @param direction The direction the blur should be applied.
  66804. * @param kernel The size of the kernel used to blur.
  66805. * @param options The required width/height ratio to downsize to before computing the render pass.
  66806. * @param camera The camera to apply the render pass to.
  66807. * @param depthMap The depth map to be used to avoid blurring accross edges
  66808. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  66809. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66810. * @param engine The engine which the post process will be applied. (default: current engine)
  66811. * @param reusable If the post process can be reused on the same frame. (default: false)
  66812. * @param textureType Type of textures used when performing the post process. (default: 0)
  66813. */
  66814. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, depthMap, imageToBlur, samplingMode, engine, reusable, textureType) {
  66815. if (imageToBlur === void 0) { imageToBlur = null; }
  66816. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66817. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66818. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) || this;
  66819. _this.direction = direction;
  66820. _this._staticDefines += "#define DOF 1\r\n";
  66821. _this.onApplyObservable.add(function (effect) {
  66822. // TODO: setTextureFromPostProcess seems to be setting the input texture instead of output of the post process passed in
  66823. if (imageToBlur != null) {
  66824. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  66825. }
  66826. effect.setTexture("depthSampler", depthMap);
  66827. if (scene.activeCamera) {
  66828. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  66829. }
  66830. });
  66831. return _this;
  66832. }
  66833. return DepthOfFieldBlurPostProcess;
  66834. }(BABYLON.BlurPostProcess));
  66835. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  66836. })(BABYLON || (BABYLON = {}));
  66837. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  66838. var BABYLON;
  66839. (function (BABYLON) {
  66840. var Bone = /** @class */ (function (_super) {
  66841. __extends(Bone, _super);
  66842. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  66843. if (parentBone === void 0) { parentBone = null; }
  66844. if (localMatrix === void 0) { localMatrix = null; }
  66845. if (restPose === void 0) { restPose = null; }
  66846. if (baseMatrix === void 0) { baseMatrix = null; }
  66847. if (index === void 0) { index = null; }
  66848. var _this = _super.call(this, name, skeleton.getScene()) || this;
  66849. _this.name = name;
  66850. _this.children = new Array();
  66851. _this.animations = new Array();
  66852. // Set this value to map this bone to a different index in the transform matrices.
  66853. // Set this value to -1 to exclude the bone from the transform matrices.
  66854. _this._index = null;
  66855. _this._worldTransform = new BABYLON.Matrix();
  66856. _this._absoluteTransform = new BABYLON.Matrix();
  66857. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  66858. _this._scaleMatrix = BABYLON.Matrix.Identity();
  66859. _this._scaleVector = BABYLON.Vector3.One();
  66860. _this._negateScaleChildren = BABYLON.Vector3.One();
  66861. _this._scalingDeterminant = 1;
  66862. _this._skeleton = skeleton;
  66863. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  66864. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  66865. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  66866. _this._index = index;
  66867. skeleton.bones.push(_this);
  66868. _this.setParent(parentBone, false);
  66869. _this._updateDifferenceMatrix();
  66870. return _this;
  66871. }
  66872. Object.defineProperty(Bone.prototype, "_matrix", {
  66873. get: function () {
  66874. return this._localMatrix;
  66875. },
  66876. set: function (val) {
  66877. if (this._localMatrix) {
  66878. this._localMatrix.copyFrom(val);
  66879. }
  66880. else {
  66881. this._localMatrix = val;
  66882. }
  66883. },
  66884. enumerable: true,
  66885. configurable: true
  66886. });
  66887. // Members
  66888. Bone.prototype.getSkeleton = function () {
  66889. return this._skeleton;
  66890. };
  66891. Bone.prototype.getParent = function () {
  66892. return this._parent;
  66893. };
  66894. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  66895. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66896. if (this._parent === parent) {
  66897. return;
  66898. }
  66899. if (this._parent) {
  66900. var index = this._parent.children.indexOf(this);
  66901. if (index !== -1) {
  66902. this._parent.children.splice(index, 1);
  66903. }
  66904. }
  66905. this._parent = parent;
  66906. if (this._parent) {
  66907. this._parent.children.push(this);
  66908. }
  66909. if (updateDifferenceMatrix) {
  66910. this._updateDifferenceMatrix();
  66911. }
  66912. };
  66913. Bone.prototype.getLocalMatrix = function () {
  66914. return this._localMatrix;
  66915. };
  66916. Bone.prototype.getBaseMatrix = function () {
  66917. return this._baseMatrix;
  66918. };
  66919. Bone.prototype.getRestPose = function () {
  66920. return this._restPose;
  66921. };
  66922. Bone.prototype.returnToRest = function () {
  66923. this.updateMatrix(this._restPose.clone());
  66924. };
  66925. Bone.prototype.getWorldMatrix = function () {
  66926. return this._worldTransform;
  66927. };
  66928. Bone.prototype.getInvertedAbsoluteTransform = function () {
  66929. return this._invertedAbsoluteTransform;
  66930. };
  66931. Bone.prototype.getAbsoluteTransform = function () {
  66932. return this._absoluteTransform;
  66933. };
  66934. Object.defineProperty(Bone.prototype, "position", {
  66935. // Properties (matches AbstractMesh properties)
  66936. get: function () {
  66937. return this.getPosition();
  66938. },
  66939. set: function (newPosition) {
  66940. this.setPosition(newPosition);
  66941. },
  66942. enumerable: true,
  66943. configurable: true
  66944. });
  66945. Object.defineProperty(Bone.prototype, "rotation", {
  66946. get: function () {
  66947. return this.getRotation();
  66948. },
  66949. set: function (newRotation) {
  66950. this.setRotation(newRotation);
  66951. },
  66952. enumerable: true,
  66953. configurable: true
  66954. });
  66955. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  66956. get: function () {
  66957. return this.getRotationQuaternion();
  66958. },
  66959. set: function (newRotation) {
  66960. this.setRotationQuaternion(newRotation);
  66961. },
  66962. enumerable: true,
  66963. configurable: true
  66964. });
  66965. Object.defineProperty(Bone.prototype, "scaling", {
  66966. get: function () {
  66967. return this.getScale();
  66968. },
  66969. set: function (newScaling) {
  66970. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  66971. },
  66972. enumerable: true,
  66973. configurable: true
  66974. });
  66975. // Methods
  66976. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  66977. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66978. this._baseMatrix = matrix.clone();
  66979. this._localMatrix = matrix.clone();
  66980. this._skeleton._markAsDirty();
  66981. if (updateDifferenceMatrix) {
  66982. this._updateDifferenceMatrix();
  66983. }
  66984. };
  66985. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  66986. if (!rootMatrix) {
  66987. rootMatrix = this._baseMatrix;
  66988. }
  66989. if (this._parent) {
  66990. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  66991. }
  66992. else {
  66993. this._absoluteTransform.copyFrom(rootMatrix);
  66994. }
  66995. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  66996. for (var index = 0; index < this.children.length; index++) {
  66997. this.children[index]._updateDifferenceMatrix();
  66998. }
  66999. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  67000. };
  67001. Bone.prototype.markAsDirty = function () {
  67002. this._currentRenderId++;
  67003. this._skeleton._markAsDirty();
  67004. };
  67005. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  67006. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  67007. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  67008. // all animation may be coming from a library skeleton, so may need to create animation
  67009. if (this.animations.length === 0) {
  67010. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  67011. this.animations[0].setKeys([]);
  67012. }
  67013. // get animation info / verify there is such a range from the source bone
  67014. var sourceRange = source.animations[0].getRange(rangeName);
  67015. if (!sourceRange) {
  67016. return false;
  67017. }
  67018. var from = sourceRange.from;
  67019. var to = sourceRange.to;
  67020. var sourceKeys = source.animations[0].getKeys();
  67021. // rescaling prep
  67022. var sourceBoneLength = source.length;
  67023. var sourceParent = source.getParent();
  67024. var parent = this.getParent();
  67025. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  67026. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  67027. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  67028. var destKeys = this.animations[0].getKeys();
  67029. // loop vars declaration
  67030. var orig;
  67031. var origTranslation;
  67032. var mat;
  67033. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  67034. orig = sourceKeys[key];
  67035. if (orig.frame >= from && orig.frame <= to) {
  67036. if (rescaleAsRequired) {
  67037. mat = orig.value.clone();
  67038. // scale based on parent ratio, when bone has parent
  67039. if (parentScalingReqd) {
  67040. origTranslation = mat.getTranslation();
  67041. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  67042. // scale based on skeleton dimension ratio when root bone, and value is passed
  67043. }
  67044. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  67045. origTranslation = mat.getTranslation();
  67046. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  67047. // use original when root bone, and no data for skelDimensionsRatio
  67048. }
  67049. else {
  67050. mat = orig.value;
  67051. }
  67052. }
  67053. else {
  67054. mat = orig.value;
  67055. }
  67056. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  67057. }
  67058. }
  67059. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  67060. return true;
  67061. };
  67062. /**
  67063. * Translate the bone in local or world space.
  67064. * @param vec The amount to translate the bone.
  67065. * @param space The space that the translation is in.
  67066. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67067. */
  67068. Bone.prototype.translate = function (vec, space, mesh) {
  67069. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67070. var lm = this.getLocalMatrix();
  67071. if (space == BABYLON.Space.LOCAL) {
  67072. lm.m[12] += vec.x;
  67073. lm.m[13] += vec.y;
  67074. lm.m[14] += vec.z;
  67075. }
  67076. else {
  67077. var wm = null;
  67078. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67079. if (mesh) {
  67080. wm = mesh.getWorldMatrix();
  67081. }
  67082. this._skeleton.computeAbsoluteTransforms();
  67083. var tmat = Bone._tmpMats[0];
  67084. var tvec = Bone._tmpVecs[0];
  67085. if (this._parent) {
  67086. if (mesh && wm) {
  67087. tmat.copyFrom(this._parent.getAbsoluteTransform());
  67088. tmat.multiplyToRef(wm, tmat);
  67089. }
  67090. else {
  67091. tmat.copyFrom(this._parent.getAbsoluteTransform());
  67092. }
  67093. }
  67094. tmat.m[12] = 0;
  67095. tmat.m[13] = 0;
  67096. tmat.m[14] = 0;
  67097. tmat.invert();
  67098. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  67099. lm.m[12] += tvec.x;
  67100. lm.m[13] += tvec.y;
  67101. lm.m[14] += tvec.z;
  67102. }
  67103. this.markAsDirty();
  67104. };
  67105. /**
  67106. * Set the postion of the bone in local or world space.
  67107. * @param position The position to set the bone.
  67108. * @param space The space that the position is in.
  67109. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67110. */
  67111. Bone.prototype.setPosition = function (position, space, mesh) {
  67112. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67113. var lm = this.getLocalMatrix();
  67114. if (space == BABYLON.Space.LOCAL) {
  67115. lm.m[12] = position.x;
  67116. lm.m[13] = position.y;
  67117. lm.m[14] = position.z;
  67118. }
  67119. else {
  67120. var wm = null;
  67121. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67122. if (mesh) {
  67123. wm = mesh.getWorldMatrix();
  67124. }
  67125. this._skeleton.computeAbsoluteTransforms();
  67126. var tmat = Bone._tmpMats[0];
  67127. var vec = Bone._tmpVecs[0];
  67128. if (this._parent) {
  67129. if (mesh && wm) {
  67130. tmat.copyFrom(this._parent.getAbsoluteTransform());
  67131. tmat.multiplyToRef(wm, tmat);
  67132. }
  67133. else {
  67134. tmat.copyFrom(this._parent.getAbsoluteTransform());
  67135. }
  67136. }
  67137. tmat.invert();
  67138. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  67139. lm.m[12] = vec.x;
  67140. lm.m[13] = vec.y;
  67141. lm.m[14] = vec.z;
  67142. }
  67143. this.markAsDirty();
  67144. };
  67145. /**
  67146. * Set the absolute postion of the bone (world space).
  67147. * @param position The position to set the bone.
  67148. * @param mesh The mesh that this bone is attached to.
  67149. */
  67150. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  67151. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  67152. };
  67153. /**
  67154. * Set the scale of the bone on the x, y and z axes.
  67155. * @param x The scale of the bone on the x axis.
  67156. * @param x The scale of the bone on the y axis.
  67157. * @param z The scale of the bone on the z axis.
  67158. * @param scaleChildren Set this to true if children of the bone should be scaled.
  67159. */
  67160. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  67161. if (scaleChildren === void 0) { scaleChildren = false; }
  67162. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  67163. if (!scaleChildren) {
  67164. this._negateScaleChildren.x = 1 / x;
  67165. this._negateScaleChildren.y = 1 / y;
  67166. this._negateScaleChildren.z = 1 / z;
  67167. }
  67168. this._syncScaleVector();
  67169. }
  67170. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  67171. };
  67172. /**
  67173. * Scale the bone on the x, y and z axes.
  67174. * @param x The amount to scale the bone on the x axis.
  67175. * @param x The amount to scale the bone on the y axis.
  67176. * @param z The amount to scale the bone on the z axis.
  67177. * @param scaleChildren Set this to true if children of the bone should be scaled.
  67178. */
  67179. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  67180. if (scaleChildren === void 0) { scaleChildren = false; }
  67181. var locMat = this.getLocalMatrix();
  67182. var origLocMat = Bone._tmpMats[0];
  67183. origLocMat.copyFrom(locMat);
  67184. var origLocMatInv = Bone._tmpMats[1];
  67185. origLocMatInv.copyFrom(origLocMat);
  67186. origLocMatInv.invert();
  67187. var scaleMat = Bone._tmpMats[2];
  67188. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  67189. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  67190. this._scaleVector.x *= x;
  67191. this._scaleVector.y *= y;
  67192. this._scaleVector.z *= z;
  67193. locMat.multiplyToRef(origLocMatInv, locMat);
  67194. locMat.multiplyToRef(scaleMat, locMat);
  67195. locMat.multiplyToRef(origLocMat, locMat);
  67196. var parent = this.getParent();
  67197. if (parent) {
  67198. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  67199. }
  67200. else {
  67201. this.getAbsoluteTransform().copyFrom(locMat);
  67202. }
  67203. var len = this.children.length;
  67204. scaleMat.invert();
  67205. for (var i = 0; i < len; i++) {
  67206. var child = this.children[i];
  67207. var cm = child.getLocalMatrix();
  67208. cm.multiplyToRef(scaleMat, cm);
  67209. var lm = child.getLocalMatrix();
  67210. lm.m[12] *= x;
  67211. lm.m[13] *= y;
  67212. lm.m[14] *= z;
  67213. }
  67214. this.computeAbsoluteTransforms();
  67215. if (scaleChildren) {
  67216. for (var i = 0; i < len; i++) {
  67217. this.children[i].scale(x, y, z, scaleChildren);
  67218. }
  67219. }
  67220. this.markAsDirty();
  67221. };
  67222. /**
  67223. * Set the yaw, pitch, and roll of the bone in local or world space.
  67224. * @param yaw The rotation of the bone on the y axis.
  67225. * @param pitch The rotation of the bone on the x axis.
  67226. * @param roll The rotation of the bone on the z axis.
  67227. * @param space The space that the axes of rotation are in.
  67228. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67229. */
  67230. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  67231. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67232. var rotMat = Bone._tmpMats[0];
  67233. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  67234. var rotMatInv = Bone._tmpMats[1];
  67235. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  67236. rotMatInv.multiplyToRef(rotMat, rotMat);
  67237. this._rotateWithMatrix(rotMat, space, mesh);
  67238. };
  67239. /**
  67240. * Rotate the bone on an axis in local or world space.
  67241. * @param axis The axis to rotate the bone on.
  67242. * @param amount The amount to rotate the bone.
  67243. * @param space The space that the axis is in.
  67244. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67245. */
  67246. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  67247. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67248. var rmat = Bone._tmpMats[0];
  67249. rmat.m[12] = 0;
  67250. rmat.m[13] = 0;
  67251. rmat.m[14] = 0;
  67252. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  67253. this._rotateWithMatrix(rmat, space, mesh);
  67254. };
  67255. /**
  67256. * Set the rotation of the bone to a particular axis angle in local or world space.
  67257. * @param axis The axis to rotate the bone on.
  67258. * @param angle The angle that the bone should be rotated to.
  67259. * @param space The space that the axis is in.
  67260. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67261. */
  67262. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  67263. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67264. var rotMat = Bone._tmpMats[0];
  67265. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  67266. var rotMatInv = Bone._tmpMats[1];
  67267. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  67268. rotMatInv.multiplyToRef(rotMat, rotMat);
  67269. this._rotateWithMatrix(rotMat, space, mesh);
  67270. };
  67271. /**
  67272. * Set the euler rotation of the bone in local of world space.
  67273. * @param rotation The euler rotation that the bone should be set to.
  67274. * @param space The space that the rotation is in.
  67275. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67276. */
  67277. Bone.prototype.setRotation = function (rotation, space, mesh) {
  67278. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67279. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  67280. };
  67281. /**
  67282. * Set the quaternion rotation of the bone in local of world space.
  67283. * @param quat The quaternion rotation that the bone should be set to.
  67284. * @param space The space that the rotation is in.
  67285. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67286. */
  67287. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  67288. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67289. var rotMatInv = Bone._tmpMats[0];
  67290. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  67291. var rotMat = Bone._tmpMats[1];
  67292. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  67293. rotMatInv.multiplyToRef(rotMat, rotMat);
  67294. this._rotateWithMatrix(rotMat, space, mesh);
  67295. };
  67296. /**
  67297. * Set the rotation matrix of the bone in local of world space.
  67298. * @param rotMat The rotation matrix that the bone should be set to.
  67299. * @param space The space that the rotation is in.
  67300. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67301. */
  67302. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  67303. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67304. var rotMatInv = Bone._tmpMats[0];
  67305. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  67306. var rotMat2 = Bone._tmpMats[1];
  67307. rotMat2.copyFrom(rotMat);
  67308. rotMatInv.multiplyToRef(rotMat, rotMat2);
  67309. this._rotateWithMatrix(rotMat2, space, mesh);
  67310. };
  67311. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  67312. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67313. var lmat = this.getLocalMatrix();
  67314. var lx = lmat.m[12];
  67315. var ly = lmat.m[13];
  67316. var lz = lmat.m[14];
  67317. var parent = this.getParent();
  67318. var parentScale = Bone._tmpMats[3];
  67319. var parentScaleInv = Bone._tmpMats[4];
  67320. if (parent) {
  67321. if (space == BABYLON.Space.WORLD) {
  67322. if (mesh) {
  67323. parentScale.copyFrom(mesh.getWorldMatrix());
  67324. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  67325. }
  67326. else {
  67327. parentScale.copyFrom(parent.getAbsoluteTransform());
  67328. }
  67329. }
  67330. else {
  67331. parentScale = parent._scaleMatrix;
  67332. }
  67333. parentScaleInv.copyFrom(parentScale);
  67334. parentScaleInv.invert();
  67335. lmat.multiplyToRef(parentScale, lmat);
  67336. lmat.multiplyToRef(rmat, lmat);
  67337. lmat.multiplyToRef(parentScaleInv, lmat);
  67338. }
  67339. else {
  67340. if (space == BABYLON.Space.WORLD && mesh) {
  67341. parentScale.copyFrom(mesh.getWorldMatrix());
  67342. parentScaleInv.copyFrom(parentScale);
  67343. parentScaleInv.invert();
  67344. lmat.multiplyToRef(parentScale, lmat);
  67345. lmat.multiplyToRef(rmat, lmat);
  67346. lmat.multiplyToRef(parentScaleInv, lmat);
  67347. }
  67348. else {
  67349. lmat.multiplyToRef(rmat, lmat);
  67350. }
  67351. }
  67352. lmat.m[12] = lx;
  67353. lmat.m[13] = ly;
  67354. lmat.m[14] = lz;
  67355. this.computeAbsoluteTransforms();
  67356. this.markAsDirty();
  67357. };
  67358. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  67359. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67360. if (space == BABYLON.Space.WORLD) {
  67361. var scaleMatrix = Bone._tmpMats[2];
  67362. scaleMatrix.copyFrom(this._scaleMatrix);
  67363. rotMatInv.copyFrom(this.getAbsoluteTransform());
  67364. if (mesh) {
  67365. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  67366. var meshScale = Bone._tmpMats[3];
  67367. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  67368. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  67369. }
  67370. rotMatInv.invert();
  67371. scaleMatrix.m[0] *= this._scalingDeterminant;
  67372. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  67373. }
  67374. else {
  67375. rotMatInv.copyFrom(this.getLocalMatrix());
  67376. rotMatInv.invert();
  67377. var scaleMatrix = Bone._tmpMats[2];
  67378. scaleMatrix.copyFrom(this._scaleMatrix);
  67379. if (this._parent) {
  67380. var pscaleMatrix = Bone._tmpMats[3];
  67381. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  67382. pscaleMatrix.invert();
  67383. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  67384. }
  67385. else {
  67386. scaleMatrix.m[0] *= this._scalingDeterminant;
  67387. }
  67388. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  67389. }
  67390. };
  67391. /**
  67392. * Get the scale of the bone
  67393. * @returns the scale of the bone
  67394. */
  67395. Bone.prototype.getScale = function () {
  67396. return this._scaleVector.clone();
  67397. };
  67398. /**
  67399. * Copy the scale of the bone to a vector3.
  67400. * @param result The vector3 to copy the scale to
  67401. */
  67402. Bone.prototype.getScaleToRef = function (result) {
  67403. result.copyFrom(this._scaleVector);
  67404. };
  67405. /**
  67406. * Get the position of the bone in local or world space.
  67407. * @param space The space that the returned position is in.
  67408. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67409. * @returns The position of the bone
  67410. */
  67411. Bone.prototype.getPosition = function (space, mesh) {
  67412. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67413. if (mesh === void 0) { mesh = null; }
  67414. var pos = BABYLON.Vector3.Zero();
  67415. this.getPositionToRef(space, mesh, pos);
  67416. return pos;
  67417. };
  67418. /**
  67419. * Copy the position of the bone to a vector3 in local or world space.
  67420. * @param space The space that the returned position is in.
  67421. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67422. * @param result The vector3 to copy the position to.
  67423. */
  67424. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  67425. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67426. if (space == BABYLON.Space.LOCAL) {
  67427. var lm = this.getLocalMatrix();
  67428. result.x = lm.m[12];
  67429. result.y = lm.m[13];
  67430. result.z = lm.m[14];
  67431. }
  67432. else {
  67433. var wm = null;
  67434. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67435. if (mesh) {
  67436. wm = mesh.getWorldMatrix();
  67437. }
  67438. this._skeleton.computeAbsoluteTransforms();
  67439. var tmat = Bone._tmpMats[0];
  67440. if (mesh && wm) {
  67441. tmat.copyFrom(this.getAbsoluteTransform());
  67442. tmat.multiplyToRef(wm, tmat);
  67443. }
  67444. else {
  67445. tmat = this.getAbsoluteTransform();
  67446. }
  67447. result.x = tmat.m[12];
  67448. result.y = tmat.m[13];
  67449. result.z = tmat.m[14];
  67450. }
  67451. };
  67452. /**
  67453. * Get the absolute position of the bone (world space).
  67454. * @param mesh The mesh that this bone is attached to.
  67455. * @returns The absolute position of the bone
  67456. */
  67457. Bone.prototype.getAbsolutePosition = function (mesh) {
  67458. if (mesh === void 0) { mesh = null; }
  67459. var pos = BABYLON.Vector3.Zero();
  67460. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  67461. return pos;
  67462. };
  67463. /**
  67464. * Copy the absolute position of the bone (world space) to the result param.
  67465. * @param mesh The mesh that this bone is attached to.
  67466. * @param result The vector3 to copy the absolute position to.
  67467. */
  67468. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  67469. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  67470. };
  67471. /**
  67472. * Compute the absolute transforms of this bone and its children.
  67473. */
  67474. Bone.prototype.computeAbsoluteTransforms = function () {
  67475. if (this._parent) {
  67476. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  67477. }
  67478. else {
  67479. this._absoluteTransform.copyFrom(this._localMatrix);
  67480. var poseMatrix = this._skeleton.getPoseMatrix();
  67481. if (poseMatrix) {
  67482. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  67483. }
  67484. }
  67485. var children = this.children;
  67486. var len = children.length;
  67487. for (var i = 0; i < len; i++) {
  67488. children[i].computeAbsoluteTransforms();
  67489. }
  67490. };
  67491. Bone.prototype._syncScaleVector = function () {
  67492. var lm = this.getLocalMatrix();
  67493. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  67494. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  67495. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  67496. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  67497. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  67498. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  67499. this._scaleVector.x = xs * Math.sqrt(xsq);
  67500. this._scaleVector.y = ys * Math.sqrt(ysq);
  67501. this._scaleVector.z = zs * Math.sqrt(zsq);
  67502. if (this._parent) {
  67503. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  67504. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  67505. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  67506. }
  67507. 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);
  67508. };
  67509. /**
  67510. * Get the world direction from an axis that is in the local space of the bone.
  67511. * @param localAxis The local direction that is used to compute the world direction.
  67512. * @param mesh The mesh that this bone is attached to.
  67513. * @returns The world direction
  67514. */
  67515. Bone.prototype.getDirection = function (localAxis, mesh) {
  67516. if (mesh === void 0) { mesh = null; }
  67517. var result = BABYLON.Vector3.Zero();
  67518. this.getDirectionToRef(localAxis, mesh, result);
  67519. return result;
  67520. };
  67521. /**
  67522. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  67523. * @param localAxis The local direction that is used to compute the world direction.
  67524. * @param mesh The mesh that this bone is attached to.
  67525. * @param result The vector3 that the world direction will be copied to.
  67526. */
  67527. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  67528. if (mesh === void 0) { mesh = null; }
  67529. var wm = null;
  67530. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67531. if (mesh) {
  67532. wm = mesh.getWorldMatrix();
  67533. }
  67534. this._skeleton.computeAbsoluteTransforms();
  67535. var mat = Bone._tmpMats[0];
  67536. mat.copyFrom(this.getAbsoluteTransform());
  67537. if (mesh && wm) {
  67538. mat.multiplyToRef(wm, mat);
  67539. }
  67540. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  67541. result.normalize();
  67542. };
  67543. /**
  67544. * Get the euler rotation of the bone in local or world space.
  67545. * @param space The space that the rotation should be in.
  67546. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67547. * @returns The euler rotation
  67548. */
  67549. Bone.prototype.getRotation = function (space, mesh) {
  67550. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67551. if (mesh === void 0) { mesh = null; }
  67552. var result = BABYLON.Vector3.Zero();
  67553. this.getRotationToRef(space, mesh, result);
  67554. return result;
  67555. };
  67556. /**
  67557. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  67558. * @param space The space that the rotation should be in.
  67559. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67560. * @param result The vector3 that the rotation should be copied to.
  67561. */
  67562. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  67563. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67564. if (mesh === void 0) { mesh = null; }
  67565. var quat = Bone._tmpQuat;
  67566. this.getRotationQuaternionToRef(space, mesh, quat);
  67567. quat.toEulerAnglesToRef(result);
  67568. };
  67569. /**
  67570. * Get the quaternion rotation of the bone in either local or world space.
  67571. * @param space The space that the rotation should be in.
  67572. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67573. * @returns The quaternion rotation
  67574. */
  67575. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  67576. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67577. if (mesh === void 0) { mesh = null; }
  67578. var result = BABYLON.Quaternion.Identity();
  67579. this.getRotationQuaternionToRef(space, mesh, result);
  67580. return result;
  67581. };
  67582. /**
  67583. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  67584. * @param space The space that the rotation should be in.
  67585. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67586. * @param result The quaternion that the rotation should be copied to.
  67587. */
  67588. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  67589. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67590. if (mesh === void 0) { mesh = null; }
  67591. if (space == BABYLON.Space.LOCAL) {
  67592. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  67593. }
  67594. else {
  67595. var mat = Bone._tmpMats[0];
  67596. var amat = this.getAbsoluteTransform();
  67597. if (mesh) {
  67598. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  67599. }
  67600. else {
  67601. mat.copyFrom(amat);
  67602. }
  67603. mat.m[0] *= this._scalingDeterminant;
  67604. mat.m[1] *= this._scalingDeterminant;
  67605. mat.m[2] *= this._scalingDeterminant;
  67606. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  67607. }
  67608. };
  67609. /**
  67610. * Get the rotation matrix of the bone in local or world space.
  67611. * @param space The space that the rotation should be in.
  67612. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67613. * @returns The rotation matrix
  67614. */
  67615. Bone.prototype.getRotationMatrix = function (space, mesh) {
  67616. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67617. var result = BABYLON.Matrix.Identity();
  67618. this.getRotationMatrixToRef(space, mesh, result);
  67619. return result;
  67620. };
  67621. /**
  67622. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  67623. * @param space The space that the rotation should be in.
  67624. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  67625. * @param result The quaternion that the rotation should be copied to.
  67626. */
  67627. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  67628. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  67629. if (space == BABYLON.Space.LOCAL) {
  67630. this.getLocalMatrix().getRotationMatrixToRef(result);
  67631. }
  67632. else {
  67633. var mat = Bone._tmpMats[0];
  67634. var amat = this.getAbsoluteTransform();
  67635. if (mesh) {
  67636. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  67637. }
  67638. else {
  67639. mat.copyFrom(amat);
  67640. }
  67641. mat.m[0] *= this._scalingDeterminant;
  67642. mat.m[1] *= this._scalingDeterminant;
  67643. mat.m[2] *= this._scalingDeterminant;
  67644. mat.getRotationMatrixToRef(result);
  67645. }
  67646. };
  67647. /**
  67648. * Get the world position of a point that is in the local space of the bone.
  67649. * @param position The local position
  67650. * @param mesh The mesh that this bone is attached to.
  67651. * @returns The world position
  67652. */
  67653. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  67654. if (mesh === void 0) { mesh = null; }
  67655. var result = BABYLON.Vector3.Zero();
  67656. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  67657. return result;
  67658. };
  67659. /**
  67660. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  67661. * @param position The local position
  67662. * @param mesh The mesh that this bone is attached to.
  67663. * @param result The vector3 that the world position should be copied to.
  67664. */
  67665. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  67666. if (mesh === void 0) { mesh = null; }
  67667. var wm = null;
  67668. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67669. if (mesh) {
  67670. wm = mesh.getWorldMatrix();
  67671. }
  67672. this._skeleton.computeAbsoluteTransforms();
  67673. var tmat = Bone._tmpMats[0];
  67674. if (mesh && wm) {
  67675. tmat.copyFrom(this.getAbsoluteTransform());
  67676. tmat.multiplyToRef(wm, tmat);
  67677. }
  67678. else {
  67679. tmat = this.getAbsoluteTransform();
  67680. }
  67681. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  67682. };
  67683. /**
  67684. * Get the local position of a point that is in world space.
  67685. * @param position The world position
  67686. * @param mesh The mesh that this bone is attached to.
  67687. * @returns The local position
  67688. */
  67689. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  67690. if (mesh === void 0) { mesh = null; }
  67691. var result = BABYLON.Vector3.Zero();
  67692. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  67693. return result;
  67694. };
  67695. /**
  67696. * Get the local position of a point that is in world space and copy it to the result param.
  67697. * @param position The world position
  67698. * @param mesh The mesh that this bone is attached to.
  67699. * @param result The vector3 that the local position should be copied to.
  67700. */
  67701. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  67702. if (mesh === void 0) { mesh = null; }
  67703. var wm = null;
  67704. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67705. if (mesh) {
  67706. wm = mesh.getWorldMatrix();
  67707. }
  67708. this._skeleton.computeAbsoluteTransforms();
  67709. var tmat = Bone._tmpMats[0];
  67710. tmat.copyFrom(this.getAbsoluteTransform());
  67711. if (mesh && wm) {
  67712. tmat.multiplyToRef(wm, tmat);
  67713. }
  67714. tmat.invert();
  67715. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  67716. };
  67717. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67718. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  67719. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67720. return Bone;
  67721. }(BABYLON.Node));
  67722. BABYLON.Bone = Bone;
  67723. })(BABYLON || (BABYLON = {}));
  67724. //# sourceMappingURL=babylon.bone.js.map
  67725. var BABYLON;
  67726. (function (BABYLON) {
  67727. var BoneIKController = /** @class */ (function () {
  67728. function BoneIKController(mesh, bone, options) {
  67729. this.targetPosition = BABYLON.Vector3.Zero();
  67730. this.poleTargetPosition = BABYLON.Vector3.Zero();
  67731. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  67732. this.poleAngle = 0;
  67733. this.slerpAmount = 1;
  67734. this._bone1Quat = BABYLON.Quaternion.Identity();
  67735. this._bone1Mat = BABYLON.Matrix.Identity();
  67736. this._bone2Ang = Math.PI;
  67737. this._maxAngle = Math.PI;
  67738. this._rightHandedSystem = false;
  67739. this._bendAxis = BABYLON.Vector3.Right();
  67740. this._slerping = false;
  67741. this._adjustRoll = 0;
  67742. this._bone2 = bone;
  67743. this._bone1 = bone.getParent();
  67744. if (!this._bone1) {
  67745. return;
  67746. }
  67747. this.mesh = mesh;
  67748. var bonePos = bone.getPosition();
  67749. if (bone.getAbsoluteTransform().determinant() > 0) {
  67750. this._rightHandedSystem = true;
  67751. this._bendAxis.x = 0;
  67752. this._bendAxis.y = 0;
  67753. this._bendAxis.z = -1;
  67754. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  67755. this._adjustRoll = Math.PI * .5;
  67756. this._bendAxis.z = 1;
  67757. }
  67758. }
  67759. if (this._bone1.length) {
  67760. var boneScale1 = this._bone1.getScale();
  67761. var boneScale2 = this._bone2.getScale();
  67762. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  67763. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  67764. }
  67765. else if (this._bone1.children[0]) {
  67766. mesh.computeWorldMatrix(true);
  67767. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  67768. var pos2 = this._bone2.getAbsolutePosition(mesh);
  67769. var pos3 = this._bone1.getAbsolutePosition(mesh);
  67770. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  67771. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  67772. }
  67773. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  67774. this.maxAngle = Math.PI;
  67775. if (options) {
  67776. if (options.targetMesh) {
  67777. this.targetMesh = options.targetMesh;
  67778. this.targetMesh.computeWorldMatrix(true);
  67779. }
  67780. if (options.poleTargetMesh) {
  67781. this.poleTargetMesh = options.poleTargetMesh;
  67782. this.poleTargetMesh.computeWorldMatrix(true);
  67783. }
  67784. else if (options.poleTargetBone) {
  67785. this.poleTargetBone = options.poleTargetBone;
  67786. }
  67787. else if (this._bone1.getParent()) {
  67788. this.poleTargetBone = this._bone1.getParent();
  67789. }
  67790. if (options.poleTargetLocalOffset) {
  67791. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  67792. }
  67793. if (options.poleAngle) {
  67794. this.poleAngle = options.poleAngle;
  67795. }
  67796. if (options.bendAxis) {
  67797. this._bendAxis.copyFrom(options.bendAxis);
  67798. }
  67799. if (options.maxAngle) {
  67800. this.maxAngle = options.maxAngle;
  67801. }
  67802. if (options.slerpAmount) {
  67803. this.slerpAmount = options.slerpAmount;
  67804. }
  67805. }
  67806. }
  67807. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  67808. get: function () {
  67809. return this._maxAngle;
  67810. },
  67811. set: function (value) {
  67812. this._setMaxAngle(value);
  67813. },
  67814. enumerable: true,
  67815. configurable: true
  67816. });
  67817. BoneIKController.prototype._setMaxAngle = function (ang) {
  67818. if (ang < 0) {
  67819. ang = 0;
  67820. }
  67821. if (ang > Math.PI || ang == undefined) {
  67822. ang = Math.PI;
  67823. }
  67824. this._maxAngle = ang;
  67825. var a = this._bone1Length;
  67826. var b = this._bone2Length;
  67827. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  67828. };
  67829. BoneIKController.prototype.update = function () {
  67830. var bone1 = this._bone1;
  67831. if (!bone1) {
  67832. return;
  67833. }
  67834. var target = this.targetPosition;
  67835. var poleTarget = this.poleTargetPosition;
  67836. var mat1 = BoneIKController._tmpMats[0];
  67837. var mat2 = BoneIKController._tmpMats[1];
  67838. if (this.targetMesh) {
  67839. target.copyFrom(this.targetMesh.getAbsolutePosition());
  67840. }
  67841. if (this.poleTargetBone) {
  67842. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  67843. }
  67844. else if (this.poleTargetMesh) {
  67845. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  67846. }
  67847. var bonePos = BoneIKController._tmpVecs[0];
  67848. var zaxis = BoneIKController._tmpVecs[1];
  67849. var xaxis = BoneIKController._tmpVecs[2];
  67850. var yaxis = BoneIKController._tmpVecs[3];
  67851. var upAxis = BoneIKController._tmpVecs[4];
  67852. var _tmpQuat = BoneIKController._tmpQuat;
  67853. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  67854. poleTarget.subtractToRef(bonePos, upAxis);
  67855. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  67856. upAxis.y = 1;
  67857. }
  67858. else {
  67859. upAxis.normalize();
  67860. }
  67861. target.subtractToRef(bonePos, yaxis);
  67862. yaxis.normalize();
  67863. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  67864. zaxis.normalize();
  67865. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  67866. xaxis.normalize();
  67867. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  67868. var a = this._bone1Length;
  67869. var b = this._bone2Length;
  67870. var c = BABYLON.Vector3.Distance(bonePos, target);
  67871. if (this._maxReach > 0) {
  67872. c = Math.min(this._maxReach, c);
  67873. }
  67874. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  67875. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  67876. if (acosa > 1) {
  67877. acosa = 1;
  67878. }
  67879. if (acosb > 1) {
  67880. acosb = 1;
  67881. }
  67882. if (acosa < -1) {
  67883. acosa = -1;
  67884. }
  67885. if (acosb < -1) {
  67886. acosb = -1;
  67887. }
  67888. var angA = Math.acos(acosa);
  67889. var angB = Math.acos(acosb);
  67890. var angC = -angA - angB;
  67891. if (this._rightHandedSystem) {
  67892. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  67893. mat2.multiplyToRef(mat1, mat1);
  67894. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  67895. mat2.multiplyToRef(mat1, mat1);
  67896. }
  67897. else {
  67898. var _tmpVec = BoneIKController._tmpVecs[5];
  67899. _tmpVec.copyFrom(this._bendAxis);
  67900. _tmpVec.x *= -1;
  67901. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  67902. mat2.multiplyToRef(mat1, mat1);
  67903. }
  67904. if (this.poleAngle) {
  67905. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  67906. mat1.multiplyToRef(mat2, mat1);
  67907. }
  67908. if (this._bone1) {
  67909. if (this.slerpAmount < 1) {
  67910. if (!this._slerping) {
  67911. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  67912. }
  67913. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  67914. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  67915. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  67916. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  67917. this._slerping = true;
  67918. }
  67919. else {
  67920. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  67921. this._bone1Mat.copyFrom(mat1);
  67922. this._slerping = false;
  67923. }
  67924. }
  67925. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  67926. this._bone2Ang = angC;
  67927. };
  67928. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67929. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  67930. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67931. return BoneIKController;
  67932. }());
  67933. BABYLON.BoneIKController = BoneIKController;
  67934. })(BABYLON || (BABYLON = {}));
  67935. //# sourceMappingURL=babylon.boneIKController.js.map
  67936. var BABYLON;
  67937. (function (BABYLON) {
  67938. var BoneLookController = /** @class */ (function () {
  67939. /**
  67940. * Create a BoneLookController
  67941. * @param mesh the mesh that the bone belongs to
  67942. * @param bone the bone that will be looking to the target
  67943. * @param target the target Vector3 to look at
  67944. * @param settings optional settings:
  67945. * - maxYaw: the maximum angle the bone will yaw to
  67946. * - minYaw: the minimum angle the bone will yaw to
  67947. * - maxPitch: the maximum angle the bone will pitch to
  67948. * - minPitch: the minimum angle the bone will yaw to
  67949. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  67950. * - upAxis: the up axis of the coordinate system
  67951. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67952. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  67953. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  67954. * - adjustYaw: used to make an adjustment to the yaw of the bone
  67955. * - adjustPitch: used to make an adjustment to the pitch of the bone
  67956. * - adjustRoll: used to make an adjustment to the roll of the bone
  67957. **/
  67958. function BoneLookController(mesh, bone, target, options) {
  67959. /**
  67960. * The up axis of the coordinate system that is used when the bone is rotated.
  67961. */
  67962. this.upAxis = BABYLON.Vector3.Up();
  67963. /**
  67964. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67965. */
  67966. this.upAxisSpace = BABYLON.Space.LOCAL;
  67967. /**
  67968. * Used to make an adjustment to the yaw of the bone.
  67969. */
  67970. this.adjustYaw = 0;
  67971. /**
  67972. * Used to make an adjustment to the pitch of the bone.
  67973. */
  67974. this.adjustPitch = 0;
  67975. /**
  67976. * Used to make an adjustment to the roll of the bone.
  67977. */
  67978. this.adjustRoll = 0;
  67979. /**
  67980. * 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).
  67981. */
  67982. this.slerpAmount = 1;
  67983. this._boneQuat = BABYLON.Quaternion.Identity();
  67984. this._slerping = false;
  67985. this._firstFrameSkipped = false;
  67986. this._fowardAxis = BABYLON.Vector3.Forward();
  67987. this.mesh = mesh;
  67988. this.bone = bone;
  67989. this.target = target;
  67990. if (options) {
  67991. if (options.adjustYaw) {
  67992. this.adjustYaw = options.adjustYaw;
  67993. }
  67994. if (options.adjustPitch) {
  67995. this.adjustPitch = options.adjustPitch;
  67996. }
  67997. if (options.adjustRoll) {
  67998. this.adjustRoll = options.adjustRoll;
  67999. }
  68000. if (options.maxYaw != null) {
  68001. this.maxYaw = options.maxYaw;
  68002. }
  68003. else {
  68004. this.maxYaw = Math.PI;
  68005. }
  68006. if (options.minYaw != null) {
  68007. this.minYaw = options.minYaw;
  68008. }
  68009. else {
  68010. this.minYaw = -Math.PI;
  68011. }
  68012. if (options.maxPitch != null) {
  68013. this.maxPitch = options.maxPitch;
  68014. }
  68015. else {
  68016. this.maxPitch = Math.PI;
  68017. }
  68018. if (options.minPitch != null) {
  68019. this.minPitch = options.minPitch;
  68020. }
  68021. else {
  68022. this.minPitch = -Math.PI;
  68023. }
  68024. if (options.slerpAmount != null) {
  68025. this.slerpAmount = options.slerpAmount;
  68026. }
  68027. if (options.upAxis != null) {
  68028. this.upAxis = options.upAxis;
  68029. }
  68030. if (options.upAxisSpace != null) {
  68031. this.upAxisSpace = options.upAxisSpace;
  68032. }
  68033. if (options.yawAxis != null || options.pitchAxis != null) {
  68034. var newYawAxis = BABYLON.Axis.Y;
  68035. var newPitchAxis = BABYLON.Axis.X;
  68036. if (options.yawAxis != null) {
  68037. newYawAxis = options.yawAxis.clone();
  68038. newYawAxis.normalize();
  68039. }
  68040. if (options.pitchAxis != null) {
  68041. newPitchAxis = options.pitchAxis.clone();
  68042. newPitchAxis.normalize();
  68043. }
  68044. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  68045. this._transformYawPitch = BABYLON.Matrix.Identity();
  68046. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  68047. this._transformYawPitchInv = this._transformYawPitch.clone();
  68048. this._transformYawPitch.invert();
  68049. }
  68050. }
  68051. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  68052. this.upAxisSpace = BABYLON.Space.LOCAL;
  68053. }
  68054. }
  68055. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  68056. /**
  68057. * Get/set the minimum yaw angle that the bone can look to.
  68058. */
  68059. get: function () {
  68060. return this._minYaw;
  68061. },
  68062. set: function (value) {
  68063. this._minYaw = value;
  68064. this._minYawSin = Math.sin(value);
  68065. this._minYawCos = Math.cos(value);
  68066. if (this._maxYaw != null) {
  68067. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  68068. this._yawRange = this._maxYaw - this._minYaw;
  68069. }
  68070. },
  68071. enumerable: true,
  68072. configurable: true
  68073. });
  68074. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  68075. /**
  68076. * Get/set the maximum yaw angle that the bone can look to.
  68077. */
  68078. get: function () {
  68079. return this._maxYaw;
  68080. },
  68081. set: function (value) {
  68082. this._maxYaw = value;
  68083. this._maxYawSin = Math.sin(value);
  68084. this._maxYawCos = Math.cos(value);
  68085. if (this._minYaw != null) {
  68086. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  68087. this._yawRange = this._maxYaw - this._minYaw;
  68088. }
  68089. },
  68090. enumerable: true,
  68091. configurable: true
  68092. });
  68093. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  68094. /**
  68095. * Get/set the minimum pitch angle that the bone can look to.
  68096. */
  68097. get: function () {
  68098. return this._minPitch;
  68099. },
  68100. set: function (value) {
  68101. this._minPitch = value;
  68102. this._minPitchTan = Math.tan(value);
  68103. },
  68104. enumerable: true,
  68105. configurable: true
  68106. });
  68107. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  68108. /**
  68109. * Get/set the maximum pitch angle that the bone can look to.
  68110. */
  68111. get: function () {
  68112. return this._maxPitch;
  68113. },
  68114. set: function (value) {
  68115. this._maxPitch = value;
  68116. this._maxPitchTan = Math.tan(value);
  68117. },
  68118. enumerable: true,
  68119. configurable: true
  68120. });
  68121. /**
  68122. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  68123. */
  68124. BoneLookController.prototype.update = function () {
  68125. //skip the first frame when slerping so that the mesh rotation is correct
  68126. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  68127. this._firstFrameSkipped = true;
  68128. return;
  68129. }
  68130. var bone = this.bone;
  68131. var bonePos = BoneLookController._tmpVecs[0];
  68132. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  68133. var target = this.target;
  68134. var _tmpMat1 = BoneLookController._tmpMats[0];
  68135. var _tmpMat2 = BoneLookController._tmpMats[1];
  68136. var mesh = this.mesh;
  68137. var parentBone = bone.getParent();
  68138. var upAxis = BoneLookController._tmpVecs[1];
  68139. upAxis.copyFrom(this.upAxis);
  68140. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  68141. if (this._transformYawPitch) {
  68142. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  68143. }
  68144. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  68145. }
  68146. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  68147. mesh.getDirectionToRef(upAxis, upAxis);
  68148. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  68149. upAxis.normalize();
  68150. }
  68151. }
  68152. var checkYaw = false;
  68153. var checkPitch = false;
  68154. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  68155. checkYaw = true;
  68156. }
  68157. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  68158. checkPitch = true;
  68159. }
  68160. if (checkYaw || checkPitch) {
  68161. var spaceMat = BoneLookController._tmpMats[2];
  68162. var spaceMatInv = BoneLookController._tmpMats[3];
  68163. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  68164. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  68165. }
  68166. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  68167. spaceMat.copyFrom(mesh.getWorldMatrix());
  68168. }
  68169. else {
  68170. var forwardAxis = BoneLookController._tmpVecs[2];
  68171. forwardAxis.copyFrom(this._fowardAxis);
  68172. if (this._transformYawPitch) {
  68173. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  68174. }
  68175. if (parentBone) {
  68176. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  68177. }
  68178. else {
  68179. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  68180. }
  68181. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  68182. rightAxis.normalize();
  68183. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  68184. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  68185. }
  68186. spaceMat.invertToRef(spaceMatInv);
  68187. var xzlen = null;
  68188. if (checkPitch) {
  68189. var localTarget = BoneLookController._tmpVecs[3];
  68190. target.subtractToRef(bonePos, localTarget);
  68191. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  68192. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  68193. var pitch = Math.atan2(localTarget.y, xzlen);
  68194. var newPitch = pitch;
  68195. if (pitch > this._maxPitch) {
  68196. localTarget.y = this._maxPitchTan * xzlen;
  68197. newPitch = this._maxPitch;
  68198. }
  68199. else if (pitch < this._minPitch) {
  68200. localTarget.y = this._minPitchTan * xzlen;
  68201. newPitch = this._minPitch;
  68202. }
  68203. if (pitch != newPitch) {
  68204. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  68205. localTarget.addInPlace(bonePos);
  68206. target = localTarget;
  68207. }
  68208. }
  68209. if (checkYaw) {
  68210. var localTarget = BoneLookController._tmpVecs[4];
  68211. target.subtractToRef(bonePos, localTarget);
  68212. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  68213. var yaw = Math.atan2(localTarget.x, localTarget.z);
  68214. var newYaw = yaw;
  68215. if (yaw > this._maxYaw || yaw < this._minYaw) {
  68216. if (xzlen == null) {
  68217. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  68218. }
  68219. if (this._yawRange > Math.PI) {
  68220. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  68221. localTarget.z = this._maxYawCos * xzlen;
  68222. localTarget.x = this._maxYawSin * xzlen;
  68223. newYaw = this._maxYaw;
  68224. }
  68225. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  68226. localTarget.z = this._minYawCos * xzlen;
  68227. localTarget.x = this._minYawSin * xzlen;
  68228. newYaw = this._minYaw;
  68229. }
  68230. }
  68231. else {
  68232. if (yaw > this._maxYaw) {
  68233. localTarget.z = this._maxYawCos * xzlen;
  68234. localTarget.x = this._maxYawSin * xzlen;
  68235. newYaw = this._maxYaw;
  68236. }
  68237. else if (yaw < this._minYaw) {
  68238. localTarget.z = this._minYawCos * xzlen;
  68239. localTarget.x = this._minYawSin * xzlen;
  68240. newYaw = this._minYaw;
  68241. }
  68242. }
  68243. }
  68244. if (this._slerping && this._yawRange > Math.PI) {
  68245. //are we going to be crossing into the min/max region?
  68246. var boneFwd = BoneLookController._tmpVecs[8];
  68247. boneFwd.copyFrom(BABYLON.Axis.Z);
  68248. if (this._transformYawPitch) {
  68249. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  68250. }
  68251. var boneRotMat = BoneLookController._tmpMats[4];
  68252. this._boneQuat.toRotationMatrix(boneRotMat);
  68253. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  68254. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  68255. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  68256. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  68257. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  68258. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  68259. if (angBtwTar > angBtwMidYaw) {
  68260. if (xzlen == null) {
  68261. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  68262. }
  68263. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  68264. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  68265. if (angBtwMin < angBtwMax) {
  68266. newYaw = boneYaw + Math.PI * .75;
  68267. localTarget.z = Math.cos(newYaw) * xzlen;
  68268. localTarget.x = Math.sin(newYaw) * xzlen;
  68269. }
  68270. else {
  68271. newYaw = boneYaw - Math.PI * .75;
  68272. localTarget.z = Math.cos(newYaw) * xzlen;
  68273. localTarget.x = Math.sin(newYaw) * xzlen;
  68274. }
  68275. }
  68276. }
  68277. if (yaw != newYaw) {
  68278. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  68279. localTarget.addInPlace(bonePos);
  68280. target = localTarget;
  68281. }
  68282. }
  68283. }
  68284. var zaxis = BoneLookController._tmpVecs[5];
  68285. var xaxis = BoneLookController._tmpVecs[6];
  68286. var yaxis = BoneLookController._tmpVecs[7];
  68287. var _tmpQuat = BoneLookController._tmpQuat;
  68288. target.subtractToRef(bonePos, zaxis);
  68289. zaxis.normalize();
  68290. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  68291. xaxis.normalize();
  68292. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  68293. yaxis.normalize();
  68294. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  68295. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  68296. return;
  68297. }
  68298. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  68299. return;
  68300. }
  68301. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  68302. return;
  68303. }
  68304. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  68305. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  68306. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  68307. }
  68308. if (this.slerpAmount < 1) {
  68309. if (!this._slerping) {
  68310. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  68311. }
  68312. if (this._transformYawPitch) {
  68313. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  68314. }
  68315. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  68316. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  68317. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  68318. this._slerping = true;
  68319. }
  68320. else {
  68321. if (this._transformYawPitch) {
  68322. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  68323. }
  68324. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  68325. this._slerping = false;
  68326. }
  68327. };
  68328. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  68329. var angDiff = ang2 - ang1;
  68330. angDiff %= Math.PI * 2;
  68331. if (angDiff > Math.PI) {
  68332. angDiff -= Math.PI * 2;
  68333. }
  68334. else if (angDiff < -Math.PI) {
  68335. angDiff += Math.PI * 2;
  68336. }
  68337. return angDiff;
  68338. };
  68339. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  68340. ang1 %= (2 * Math.PI);
  68341. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  68342. ang2 %= (2 * Math.PI);
  68343. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  68344. var ab = 0;
  68345. if (ang1 < ang2) {
  68346. ab = ang2 - ang1;
  68347. }
  68348. else {
  68349. ab = ang1 - ang2;
  68350. }
  68351. if (ab > Math.PI) {
  68352. ab = Math.PI * 2 - ab;
  68353. }
  68354. return ab;
  68355. };
  68356. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  68357. ang %= (2 * Math.PI);
  68358. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  68359. ang1 %= (2 * Math.PI);
  68360. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  68361. ang2 %= (2 * Math.PI);
  68362. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  68363. if (ang1 < ang2) {
  68364. if (ang > ang1 && ang < ang2) {
  68365. return true;
  68366. }
  68367. }
  68368. else {
  68369. if (ang > ang2 && ang < ang1) {
  68370. return true;
  68371. }
  68372. }
  68373. return false;
  68374. };
  68375. 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()];
  68376. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  68377. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  68378. return BoneLookController;
  68379. }());
  68380. BABYLON.BoneLookController = BoneLookController;
  68381. })(BABYLON || (BABYLON = {}));
  68382. //# sourceMappingURL=babylon.boneLookController.js.map
  68383. var BABYLON;
  68384. (function (BABYLON) {
  68385. var Skeleton = /** @class */ (function () {
  68386. function Skeleton(name, id, scene) {
  68387. this.name = name;
  68388. this.id = id;
  68389. this.bones = new Array();
  68390. this.needInitialSkinMatrix = false;
  68391. this._isDirty = true;
  68392. this._meshesWithPoseMatrix = new Array();
  68393. this._identity = BABYLON.Matrix.Identity();
  68394. this._ranges = {};
  68395. this._lastAbsoluteTransformsUpdateId = -1;
  68396. // Events
  68397. /**
  68398. * An event triggered before computing the skeleton's matrices
  68399. * @type {BABYLON.Observable}
  68400. */
  68401. this.onBeforeComputeObservable = new BABYLON.Observable();
  68402. this.bones = [];
  68403. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68404. scene.skeletons.push(this);
  68405. //make sure it will recalculate the matrix next time prepare is called.
  68406. this._isDirty = true;
  68407. }
  68408. // Members
  68409. Skeleton.prototype.getTransformMatrices = function (mesh) {
  68410. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  68411. return mesh._bonesTransformMatrices;
  68412. }
  68413. if (!this._transformMatrices) {
  68414. this.prepare();
  68415. }
  68416. return this._transformMatrices;
  68417. };
  68418. Skeleton.prototype.getScene = function () {
  68419. return this._scene;
  68420. };
  68421. // Methods
  68422. /**
  68423. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  68424. */
  68425. Skeleton.prototype.toString = function (fullDetails) {
  68426. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  68427. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  68428. if (fullDetails) {
  68429. ret += ", Ranges: {";
  68430. var first = true;
  68431. for (var name_1 in this._ranges) {
  68432. if (first) {
  68433. ret += ", ";
  68434. first = false;
  68435. }
  68436. ret += name_1;
  68437. }
  68438. ret += "}";
  68439. }
  68440. return ret;
  68441. };
  68442. /**
  68443. * Get bone's index searching by name
  68444. * @param {string} name is bone's name to search for
  68445. * @return {number} Indice of the bone. Returns -1 if not found
  68446. */
  68447. Skeleton.prototype.getBoneIndexByName = function (name) {
  68448. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  68449. if (this.bones[boneIndex].name === name) {
  68450. return boneIndex;
  68451. }
  68452. }
  68453. return -1;
  68454. };
  68455. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  68456. // check name not already in use
  68457. if (!this._ranges[name]) {
  68458. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  68459. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  68460. if (this.bones[i].animations[0]) {
  68461. this.bones[i].animations[0].createRange(name, from, to);
  68462. }
  68463. }
  68464. }
  68465. };
  68466. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  68467. if (deleteFrames === void 0) { deleteFrames = true; }
  68468. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  68469. if (this.bones[i].animations[0]) {
  68470. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  68471. }
  68472. }
  68473. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  68474. };
  68475. Skeleton.prototype.getAnimationRange = function (name) {
  68476. return this._ranges[name];
  68477. };
  68478. /**
  68479. * Returns as an Array, all AnimationRanges defined on this skeleton
  68480. */
  68481. Skeleton.prototype.getAnimationRanges = function () {
  68482. var animationRanges = [];
  68483. var name;
  68484. var i = 0;
  68485. for (name in this._ranges) {
  68486. animationRanges[i] = this._ranges[name];
  68487. i++;
  68488. }
  68489. return animationRanges;
  68490. };
  68491. /**
  68492. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  68493. */
  68494. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  68495. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68496. if (this._ranges[name] || !source.getAnimationRange(name)) {
  68497. return false;
  68498. }
  68499. var ret = true;
  68500. var frameOffset = this._getHighestAnimationFrame() + 1;
  68501. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  68502. var boneDict = {};
  68503. var sourceBones = source.bones;
  68504. var nBones;
  68505. var i;
  68506. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  68507. boneDict[sourceBones[i].name] = sourceBones[i];
  68508. }
  68509. if (this.bones.length !== sourceBones.length) {
  68510. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  68511. ret = false;
  68512. }
  68513. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  68514. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  68515. var boneName = this.bones[i].name;
  68516. var sourceBone = boneDict[boneName];
  68517. if (sourceBone) {
  68518. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  68519. }
  68520. else {
  68521. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  68522. ret = false;
  68523. }
  68524. }
  68525. // do not call createAnimationRange(), since it also is done to bones, which was already done
  68526. var range = source.getAnimationRange(name);
  68527. if (range) {
  68528. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  68529. }
  68530. return ret;
  68531. };
  68532. Skeleton.prototype.returnToRest = function () {
  68533. for (var index = 0; index < this.bones.length; index++) {
  68534. this.bones[index].returnToRest();
  68535. }
  68536. };
  68537. Skeleton.prototype._getHighestAnimationFrame = function () {
  68538. var ret = 0;
  68539. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  68540. if (this.bones[i].animations[0]) {
  68541. var highest = this.bones[i].animations[0].getHighestFrame();
  68542. if (ret < highest) {
  68543. ret = highest;
  68544. }
  68545. }
  68546. }
  68547. return ret;
  68548. };
  68549. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  68550. var range = this.getAnimationRange(name);
  68551. if (!range) {
  68552. return null;
  68553. }
  68554. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  68555. };
  68556. Skeleton.prototype._markAsDirty = function () {
  68557. this._isDirty = true;
  68558. };
  68559. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  68560. this._meshesWithPoseMatrix.push(mesh);
  68561. };
  68562. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  68563. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  68564. if (index > -1) {
  68565. this._meshesWithPoseMatrix.splice(index, 1);
  68566. }
  68567. };
  68568. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  68569. this.onBeforeComputeObservable.notifyObservers(this);
  68570. for (var index = 0; index < this.bones.length; index++) {
  68571. var bone = this.bones[index];
  68572. var parentBone = bone.getParent();
  68573. if (parentBone) {
  68574. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  68575. }
  68576. else {
  68577. if (initialSkinMatrix) {
  68578. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  68579. }
  68580. else {
  68581. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  68582. }
  68583. }
  68584. if (bone._index !== -1) {
  68585. var mappedIndex = bone._index === null ? index : bone._index;
  68586. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  68587. }
  68588. }
  68589. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  68590. };
  68591. Skeleton.prototype.prepare = function () {
  68592. if (!this._isDirty) {
  68593. return;
  68594. }
  68595. if (this.needInitialSkinMatrix) {
  68596. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  68597. var mesh = this._meshesWithPoseMatrix[index];
  68598. var poseMatrix = mesh.getPoseMatrix();
  68599. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  68600. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  68601. }
  68602. if (this._synchronizedWithMesh !== mesh) {
  68603. this._synchronizedWithMesh = mesh;
  68604. // Prepare bones
  68605. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  68606. var bone = this.bones[boneIndex];
  68607. if (!bone.getParent()) {
  68608. var matrix = bone.getBaseMatrix();
  68609. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  68610. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  68611. }
  68612. }
  68613. }
  68614. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  68615. }
  68616. }
  68617. else {
  68618. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  68619. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  68620. }
  68621. this._computeTransformMatrices(this._transformMatrices, null);
  68622. }
  68623. this._isDirty = false;
  68624. this._scene._activeBones.addCount(this.bones.length, false);
  68625. };
  68626. Skeleton.prototype.getAnimatables = function () {
  68627. if (!this._animatables || this._animatables.length !== this.bones.length) {
  68628. this._animatables = [];
  68629. for (var index = 0; index < this.bones.length; index++) {
  68630. this._animatables.push(this.bones[index]);
  68631. }
  68632. }
  68633. return this._animatables;
  68634. };
  68635. Skeleton.prototype.clone = function (name, id) {
  68636. var result = new Skeleton(name, id || name, this._scene);
  68637. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  68638. for (var index = 0; index < this.bones.length; index++) {
  68639. var source = this.bones[index];
  68640. var parentBone = null;
  68641. var parent_1 = source.getParent();
  68642. if (parent_1) {
  68643. var parentIndex = this.bones.indexOf(parent_1);
  68644. parentBone = result.bones[parentIndex];
  68645. }
  68646. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  68647. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  68648. }
  68649. if (this._ranges) {
  68650. result._ranges = {};
  68651. for (var rangeName in this._ranges) {
  68652. var range = this._ranges[rangeName];
  68653. if (range) {
  68654. result._ranges[rangeName] = range.clone();
  68655. }
  68656. }
  68657. }
  68658. this._isDirty = true;
  68659. return result;
  68660. };
  68661. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  68662. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  68663. this.bones.forEach(function (bone) {
  68664. bone.animations.forEach(function (animation) {
  68665. animation.enableBlending = true;
  68666. animation.blendingSpeed = blendingSpeed;
  68667. });
  68668. });
  68669. };
  68670. Skeleton.prototype.dispose = function () {
  68671. this._meshesWithPoseMatrix = [];
  68672. // Animations
  68673. this.getScene().stopAnimation(this);
  68674. // Remove from scene
  68675. this.getScene().removeSkeleton(this);
  68676. };
  68677. Skeleton.prototype.serialize = function () {
  68678. var serializationObject = {};
  68679. serializationObject.name = this.name;
  68680. serializationObject.id = this.id;
  68681. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  68682. serializationObject.bones = [];
  68683. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  68684. for (var index = 0; index < this.bones.length; index++) {
  68685. var bone = this.bones[index];
  68686. var parent_2 = bone.getParent();
  68687. var serializedBone = {
  68688. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  68689. name: bone.name,
  68690. matrix: bone.getBaseMatrix().toArray(),
  68691. rest: bone.getRestPose().toArray()
  68692. };
  68693. serializationObject.bones.push(serializedBone);
  68694. if (bone.length) {
  68695. serializedBone.length = bone.length;
  68696. }
  68697. if (bone.animations && bone.animations.length > 0) {
  68698. serializedBone.animation = bone.animations[0].serialize();
  68699. }
  68700. serializationObject.ranges = [];
  68701. for (var name in this._ranges) {
  68702. var source = this._ranges[name];
  68703. if (!source) {
  68704. continue;
  68705. }
  68706. var range = {};
  68707. range.name = name;
  68708. range.from = source.from;
  68709. range.to = source.to;
  68710. serializationObject.ranges.push(range);
  68711. }
  68712. }
  68713. return serializationObject;
  68714. };
  68715. Skeleton.Parse = function (parsedSkeleton, scene) {
  68716. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  68717. if (parsedSkeleton.dimensionsAtRest) {
  68718. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  68719. }
  68720. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  68721. var index;
  68722. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  68723. var parsedBone = parsedSkeleton.bones[index];
  68724. var parentBone = null;
  68725. if (parsedBone.parentBoneIndex > -1) {
  68726. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  68727. }
  68728. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  68729. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  68730. if (parsedBone.length) {
  68731. bone.length = parsedBone.length;
  68732. }
  68733. if (parsedBone.animation) {
  68734. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  68735. }
  68736. }
  68737. // placed after bones, so createAnimationRange can cascade down
  68738. if (parsedSkeleton.ranges) {
  68739. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  68740. var data = parsedSkeleton.ranges[index];
  68741. skeleton.createAnimationRange(data.name, data.from, data.to);
  68742. }
  68743. }
  68744. return skeleton;
  68745. };
  68746. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  68747. if (forceUpdate === void 0) { forceUpdate = false; }
  68748. var renderId = this._scene.getRenderId();
  68749. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  68750. this.bones[0].computeAbsoluteTransforms();
  68751. this._lastAbsoluteTransformsUpdateId = renderId;
  68752. }
  68753. };
  68754. Skeleton.prototype.getPoseMatrix = function () {
  68755. var poseMatrix = null;
  68756. if (this._meshesWithPoseMatrix.length > 0) {
  68757. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  68758. }
  68759. return poseMatrix;
  68760. };
  68761. Skeleton.prototype.sortBones = function () {
  68762. var bones = new Array();
  68763. var visited = new Array(this.bones.length);
  68764. for (var index = 0; index < this.bones.length; index++) {
  68765. this._sortBones(index, bones, visited);
  68766. }
  68767. this.bones = bones;
  68768. };
  68769. Skeleton.prototype._sortBones = function (index, bones, visited) {
  68770. if (visited[index]) {
  68771. return;
  68772. }
  68773. visited[index] = true;
  68774. var bone = this.bones[index];
  68775. if (bone._index === undefined) {
  68776. bone._index = index;
  68777. }
  68778. var parentBone = bone.getParent();
  68779. if (parentBone) {
  68780. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  68781. }
  68782. bones.push(bone);
  68783. };
  68784. return Skeleton;
  68785. }());
  68786. BABYLON.Skeleton = Skeleton;
  68787. })(BABYLON || (BABYLON = {}));
  68788. //# sourceMappingURL=babylon.skeleton.js.map
  68789. var BABYLON;
  68790. (function (BABYLON) {
  68791. var SphericalPolynomial = /** @class */ (function () {
  68792. function SphericalPolynomial() {
  68793. this.x = BABYLON.Vector3.Zero();
  68794. this.y = BABYLON.Vector3.Zero();
  68795. this.z = BABYLON.Vector3.Zero();
  68796. this.xx = BABYLON.Vector3.Zero();
  68797. this.yy = BABYLON.Vector3.Zero();
  68798. this.zz = BABYLON.Vector3.Zero();
  68799. this.xy = BABYLON.Vector3.Zero();
  68800. this.yz = BABYLON.Vector3.Zero();
  68801. this.zx = BABYLON.Vector3.Zero();
  68802. }
  68803. SphericalPolynomial.prototype.addAmbient = function (color) {
  68804. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68805. this.xx = this.xx.add(colorVector);
  68806. this.yy = this.yy.add(colorVector);
  68807. this.zz = this.zz.add(colorVector);
  68808. };
  68809. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  68810. var result = new SphericalPolynomial();
  68811. result.x = harmonics.L11.scale(1.02333);
  68812. result.y = harmonics.L1_1.scale(1.02333);
  68813. result.z = harmonics.L10.scale(1.02333);
  68814. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  68815. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  68816. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  68817. result.yz = harmonics.L2_1.scale(0.858086);
  68818. result.zx = harmonics.L21.scale(0.858086);
  68819. result.xy = harmonics.L2_2.scale(0.858086);
  68820. result.scale(1.0 / Math.PI);
  68821. return result;
  68822. };
  68823. SphericalPolynomial.prototype.scale = function (scale) {
  68824. this.x = this.x.scale(scale);
  68825. this.y = this.y.scale(scale);
  68826. this.z = this.z.scale(scale);
  68827. this.xx = this.xx.scale(scale);
  68828. this.yy = this.yy.scale(scale);
  68829. this.zz = this.zz.scale(scale);
  68830. this.yz = this.yz.scale(scale);
  68831. this.zx = this.zx.scale(scale);
  68832. this.xy = this.xy.scale(scale);
  68833. };
  68834. return SphericalPolynomial;
  68835. }());
  68836. BABYLON.SphericalPolynomial = SphericalPolynomial;
  68837. var SphericalHarmonics = /** @class */ (function () {
  68838. function SphericalHarmonics() {
  68839. this.L00 = BABYLON.Vector3.Zero();
  68840. this.L1_1 = BABYLON.Vector3.Zero();
  68841. this.L10 = BABYLON.Vector3.Zero();
  68842. this.L11 = BABYLON.Vector3.Zero();
  68843. this.L2_2 = BABYLON.Vector3.Zero();
  68844. this.L2_1 = BABYLON.Vector3.Zero();
  68845. this.L20 = BABYLON.Vector3.Zero();
  68846. this.L21 = BABYLON.Vector3.Zero();
  68847. this.L22 = BABYLON.Vector3.Zero();
  68848. }
  68849. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  68850. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68851. var c = colorVector.scale(deltaSolidAngle);
  68852. this.L00 = this.L00.add(c.scale(0.282095));
  68853. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  68854. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  68855. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  68856. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  68857. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  68858. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  68859. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  68860. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  68861. };
  68862. SphericalHarmonics.prototype.scale = function (scale) {
  68863. this.L00 = this.L00.scale(scale);
  68864. this.L1_1 = this.L1_1.scale(scale);
  68865. this.L10 = this.L10.scale(scale);
  68866. this.L11 = this.L11.scale(scale);
  68867. this.L2_2 = this.L2_2.scale(scale);
  68868. this.L2_1 = this.L2_1.scale(scale);
  68869. this.L20 = this.L20.scale(scale);
  68870. this.L21 = this.L21.scale(scale);
  68871. this.L22 = this.L22.scale(scale);
  68872. };
  68873. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  68874. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  68875. //
  68876. // E_lm = A_l * L_lm
  68877. //
  68878. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  68879. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  68880. // the scaling factors are given in equation 9.
  68881. // Constant (Band 0)
  68882. this.L00 = this.L00.scale(3.141593);
  68883. // Linear (Band 1)
  68884. this.L1_1 = this.L1_1.scale(2.094395);
  68885. this.L10 = this.L10.scale(2.094395);
  68886. this.L11 = this.L11.scale(2.094395);
  68887. // Quadratic (Band 2)
  68888. this.L2_2 = this.L2_2.scale(0.785398);
  68889. this.L2_1 = this.L2_1.scale(0.785398);
  68890. this.L20 = this.L20.scale(0.785398);
  68891. this.L21 = this.L21.scale(0.785398);
  68892. this.L22 = this.L22.scale(0.785398);
  68893. };
  68894. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  68895. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  68896. // L = (1/pi) * E * rho
  68897. //
  68898. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  68899. this.scale(1.0 / Math.PI);
  68900. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  68901. // (The pixel shader must apply albedo after texture fetches, etc).
  68902. };
  68903. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  68904. var result = new SphericalHarmonics();
  68905. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  68906. result.L1_1 = polynomial.y.scale(0.977204);
  68907. result.L10 = polynomial.z.scale(0.977204);
  68908. result.L11 = polynomial.x.scale(0.977204);
  68909. result.L2_2 = polynomial.xy.scale(1.16538);
  68910. result.L2_1 = polynomial.yz.scale(1.16538);
  68911. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  68912. result.L21 = polynomial.zx.scale(1.16538);
  68913. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  68914. result.scale(Math.PI);
  68915. return result;
  68916. };
  68917. return SphericalHarmonics;
  68918. }());
  68919. BABYLON.SphericalHarmonics = SphericalHarmonics;
  68920. })(BABYLON || (BABYLON = {}));
  68921. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  68922. var BABYLON;
  68923. (function (BABYLON) {
  68924. var FileFaceOrientation = /** @class */ (function () {
  68925. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  68926. this.name = name;
  68927. this.worldAxisForNormal = worldAxisForNormal;
  68928. this.worldAxisForFileX = worldAxisForFileX;
  68929. this.worldAxisForFileY = worldAxisForFileY;
  68930. }
  68931. return FileFaceOrientation;
  68932. }());
  68933. ;
  68934. /**
  68935. * Helper class dealing with the extraction of spherical polynomial dataArray
  68936. * from a cube map.
  68937. */
  68938. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  68939. function CubeMapToSphericalPolynomialTools() {
  68940. }
  68941. /**
  68942. * Converts a texture to the according Spherical Polynomial data.
  68943. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68944. *
  68945. * @param texture The texture to extract the information from.
  68946. * @return The Spherical Polynomial data.
  68947. */
  68948. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  68949. if (!texture.isCube) {
  68950. // Only supports cube Textures currently.
  68951. return null;
  68952. }
  68953. var size = texture.getSize().width;
  68954. var right = texture.readPixels(0);
  68955. var left = texture.readPixels(1);
  68956. var up;
  68957. var down;
  68958. if (texture.isRenderTarget) {
  68959. up = texture.readPixels(3);
  68960. down = texture.readPixels(2);
  68961. }
  68962. else {
  68963. up = texture.readPixels(2);
  68964. down = texture.readPixels(3);
  68965. }
  68966. var front = texture.readPixels(4);
  68967. var back = texture.readPixels(5);
  68968. var gammaSpace = texture.gammaSpace;
  68969. // Always read as RGBA.
  68970. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  68971. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68972. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68973. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68974. }
  68975. var cubeInfo = {
  68976. size: size,
  68977. right: right,
  68978. left: left,
  68979. up: up,
  68980. down: down,
  68981. front: front,
  68982. back: back,
  68983. format: format,
  68984. type: type,
  68985. gammaSpace: gammaSpace,
  68986. };
  68987. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  68988. };
  68989. /**
  68990. * Converts a cubemap to the according Spherical Polynomial data.
  68991. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68992. *
  68993. * @param cubeInfo The Cube map to extract the information from.
  68994. * @return The Spherical Polynomial data.
  68995. */
  68996. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  68997. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  68998. var totalSolidAngle = 0.0;
  68999. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  69000. var du = 2.0 / cubeInfo.size;
  69001. var dv = du;
  69002. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  69003. var minUV = du * 0.5 - 1.0;
  69004. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  69005. var fileFace = this.FileFaces[faceIndex];
  69006. var dataArray = cubeInfo[fileFace.name];
  69007. var v = minUV;
  69008. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  69009. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  69010. // Because SP is still linear, so summation is fine in that basis.
  69011. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  69012. for (var y = 0; y < cubeInfo.size; y++) {
  69013. var u = minUV;
  69014. for (var x = 0; x < cubeInfo.size; x++) {
  69015. // World direction (not normalised)
  69016. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  69017. worldDirection.normalize();
  69018. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  69019. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  69020. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  69021. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  69022. // Handle Integer types.
  69023. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69024. r /= 255;
  69025. g /= 255;
  69026. b /= 255;
  69027. }
  69028. // Handle Gamma space textures.
  69029. if (cubeInfo.gammaSpace) {
  69030. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  69031. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  69032. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  69033. }
  69034. var color = new BABYLON.Color3(r, g, b);
  69035. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  69036. totalSolidAngle += deltaSolidAngle;
  69037. u += du;
  69038. }
  69039. v += dv;
  69040. }
  69041. }
  69042. // Solid angle for entire sphere is 4*pi
  69043. var sphereSolidAngle = 4.0 * Math.PI;
  69044. // Adjust the solid angle to allow for how many faces we processed.
  69045. var facesProcessed = 6.0;
  69046. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  69047. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  69048. // This is needed because the numerical integration over the cube uses a
  69049. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  69050. // and also to compensate for accumulative error due to float precision in the summation.
  69051. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  69052. sphericalHarmonics.scale(correctionFactor);
  69053. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  69054. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  69055. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  69056. };
  69057. CubeMapToSphericalPolynomialTools.FileFaces = [
  69058. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  69059. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  69060. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  69061. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  69062. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  69063. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  69064. ];
  69065. return CubeMapToSphericalPolynomialTools;
  69066. }());
  69067. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  69068. })(BABYLON || (BABYLON = {}));
  69069. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  69070. var BABYLON;
  69071. (function (BABYLON) {
  69072. /**
  69073. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  69074. */
  69075. var PanoramaToCubeMapTools = /** @class */ (function () {
  69076. function PanoramaToCubeMapTools() {
  69077. }
  69078. /**
  69079. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  69080. *
  69081. * @param float32Array The source data.
  69082. * @param inputWidth The width of the input panorama.
  69083. * @param inputhHeight The height of the input panorama.
  69084. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  69085. * @return The cubemap data
  69086. */
  69087. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  69088. if (!float32Array) {
  69089. throw "ConvertPanoramaToCubemap: input cannot be null";
  69090. }
  69091. if (float32Array.length != inputWidth * inputHeight * 3) {
  69092. throw "ConvertPanoramaToCubemap: input size is wrong";
  69093. }
  69094. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  69095. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  69096. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  69097. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  69098. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  69099. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  69100. return {
  69101. front: textureFront,
  69102. back: textureBack,
  69103. left: textureLeft,
  69104. right: textureRight,
  69105. up: textureUp,
  69106. down: textureDown,
  69107. size: size,
  69108. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  69109. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  69110. gammaSpace: false,
  69111. };
  69112. };
  69113. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  69114. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  69115. var textureArray = new Float32Array(buffer);
  69116. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  69117. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  69118. var dy = 1 / texSize;
  69119. var fy = 0;
  69120. for (var y = 0; y < texSize; y++) {
  69121. var xv1 = faceData[0];
  69122. var xv2 = faceData[2];
  69123. for (var x = 0; x < texSize; x++) {
  69124. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  69125. v.normalize();
  69126. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  69127. // 3 channels per pixels
  69128. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  69129. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  69130. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  69131. xv1 = xv1.add(rotDX1);
  69132. xv2 = xv2.add(rotDX2);
  69133. }
  69134. fy += dy;
  69135. }
  69136. return textureArray;
  69137. };
  69138. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  69139. var theta = Math.atan2(vDir.z, vDir.x);
  69140. var phi = Math.acos(vDir.y);
  69141. while (theta < -Math.PI)
  69142. theta += 2 * Math.PI;
  69143. while (theta > Math.PI)
  69144. theta -= 2 * Math.PI;
  69145. var dx = theta / Math.PI;
  69146. var dy = phi / Math.PI;
  69147. // recenter.
  69148. dx = dx * 0.5 + 0.5;
  69149. var px = Math.round(dx * inputWidth);
  69150. if (px < 0)
  69151. px = 0;
  69152. else if (px >= inputWidth)
  69153. px = inputWidth - 1;
  69154. var py = Math.round(dy * inputHeight);
  69155. if (py < 0)
  69156. py = 0;
  69157. else if (py >= inputHeight)
  69158. py = inputHeight - 1;
  69159. var inputY = (inputHeight - py - 1);
  69160. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  69161. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  69162. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  69163. return {
  69164. r: r,
  69165. g: g,
  69166. b: b
  69167. };
  69168. };
  69169. PanoramaToCubeMapTools.FACE_FRONT = [
  69170. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  69171. new BABYLON.Vector3(1.0, -1.0, -1.0),
  69172. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  69173. new BABYLON.Vector3(1.0, 1.0, -1.0)
  69174. ];
  69175. PanoramaToCubeMapTools.FACE_BACK = [
  69176. new BABYLON.Vector3(1.0, -1.0, 1.0),
  69177. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  69178. new BABYLON.Vector3(1.0, 1.0, 1.0),
  69179. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  69180. ];
  69181. PanoramaToCubeMapTools.FACE_RIGHT = [
  69182. new BABYLON.Vector3(1.0, -1.0, -1.0),
  69183. new BABYLON.Vector3(1.0, -1.0, 1.0),
  69184. new BABYLON.Vector3(1.0, 1.0, -1.0),
  69185. new BABYLON.Vector3(1.0, 1.0, 1.0)
  69186. ];
  69187. PanoramaToCubeMapTools.FACE_LEFT = [
  69188. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  69189. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  69190. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  69191. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  69192. ];
  69193. PanoramaToCubeMapTools.FACE_DOWN = [
  69194. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  69195. new BABYLON.Vector3(1.0, 1.0, -1.0),
  69196. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  69197. new BABYLON.Vector3(1.0, 1.0, 1.0)
  69198. ];
  69199. PanoramaToCubeMapTools.FACE_UP = [
  69200. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  69201. new BABYLON.Vector3(1.0, -1.0, 1.0),
  69202. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  69203. new BABYLON.Vector3(1.0, -1.0, -1.0)
  69204. ];
  69205. return PanoramaToCubeMapTools;
  69206. }());
  69207. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  69208. })(BABYLON || (BABYLON = {}));
  69209. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  69210. var BABYLON;
  69211. (function (BABYLON) {
  69212. ;
  69213. /**
  69214. * This groups tools to convert HDR texture to native colors array.
  69215. */
  69216. var HDRTools = /** @class */ (function () {
  69217. function HDRTools() {
  69218. }
  69219. HDRTools.Ldexp = function (mantissa, exponent) {
  69220. if (exponent > 1023) {
  69221. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  69222. }
  69223. if (exponent < -1074) {
  69224. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  69225. }
  69226. return mantissa * Math.pow(2, exponent);
  69227. };
  69228. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  69229. if (exponent > 0) {
  69230. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  69231. float32array[index + 0] = red * exponent;
  69232. float32array[index + 1] = green * exponent;
  69233. float32array[index + 2] = blue * exponent;
  69234. }
  69235. else {
  69236. float32array[index + 0] = 0;
  69237. float32array[index + 1] = 0;
  69238. float32array[index + 2] = 0;
  69239. }
  69240. };
  69241. HDRTools.readStringLine = function (uint8array, startIndex) {
  69242. var line = "";
  69243. var character = "";
  69244. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  69245. character = String.fromCharCode(uint8array[i]);
  69246. if (character == "\n") {
  69247. break;
  69248. }
  69249. line += character;
  69250. }
  69251. return line;
  69252. };
  69253. /**
  69254. * Reads header information from an RGBE texture stored in a native array.
  69255. * More information on this format are available here:
  69256. * https://en.wikipedia.org/wiki/RGBE_image_format
  69257. *
  69258. * @param uint8array The binary file stored in native array.
  69259. * @return The header information.
  69260. */
  69261. HDRTools.RGBE_ReadHeader = function (uint8array) {
  69262. var height = 0;
  69263. var width = 0;
  69264. var line = this.readStringLine(uint8array, 0);
  69265. if (line[0] != '#' || line[1] != '?') {
  69266. throw "Bad HDR Format.";
  69267. }
  69268. var endOfHeader = false;
  69269. var findFormat = false;
  69270. var lineIndex = 0;
  69271. do {
  69272. lineIndex += (line.length + 1);
  69273. line = this.readStringLine(uint8array, lineIndex);
  69274. if (line == "FORMAT=32-bit_rle_rgbe") {
  69275. findFormat = true;
  69276. }
  69277. else if (line.length == 0) {
  69278. endOfHeader = true;
  69279. }
  69280. } while (!endOfHeader);
  69281. if (!findFormat) {
  69282. throw "HDR Bad header format, unsupported FORMAT";
  69283. }
  69284. lineIndex += (line.length + 1);
  69285. line = this.readStringLine(uint8array, lineIndex);
  69286. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  69287. var match = sizeRegexp.exec(line);
  69288. // TODO. Support +Y and -X if needed.
  69289. if (!match || match.length < 3) {
  69290. throw "HDR Bad header format, no size";
  69291. }
  69292. width = parseInt(match[2]);
  69293. height = parseInt(match[1]);
  69294. if (width < 8 || width > 0x7fff) {
  69295. throw "HDR Bad header format, unsupported size";
  69296. }
  69297. lineIndex += (line.length + 1);
  69298. return {
  69299. height: height,
  69300. width: width,
  69301. dataPosition: lineIndex
  69302. };
  69303. };
  69304. /**
  69305. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  69306. * This RGBE texture needs to store the information as a panorama.
  69307. *
  69308. * More information on this format are available here:
  69309. * https://en.wikipedia.org/wiki/RGBE_image_format
  69310. *
  69311. * @param buffer The binary file stored in an array buffer.
  69312. * @param size The expected size of the extracted cubemap.
  69313. * @return The Cube Map information.
  69314. */
  69315. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  69316. var uint8array = new Uint8Array(buffer);
  69317. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  69318. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  69319. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  69320. return cubeMapData;
  69321. };
  69322. /**
  69323. * Returns the pixels data extracted from an RGBE texture.
  69324. * This pixels will be stored left to right up to down in the R G B order in one array.
  69325. *
  69326. * More information on this format are available here:
  69327. * https://en.wikipedia.org/wiki/RGBE_image_format
  69328. *
  69329. * @param uint8array The binary file stored in an array buffer.
  69330. * @param hdrInfo The header information of the file.
  69331. * @return The pixels data in RGB right to left up to down order.
  69332. */
  69333. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  69334. // Keep for multi format supports.
  69335. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  69336. };
  69337. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  69338. var num_scanlines = hdrInfo.height;
  69339. var scanline_width = hdrInfo.width;
  69340. var a, b, c, d, count;
  69341. var dataIndex = hdrInfo.dataPosition;
  69342. var index = 0, endIndex = 0, i = 0;
  69343. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  69344. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  69345. // 3 channels of 4 bytes per pixel in float.
  69346. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  69347. var resultArray = new Float32Array(resultBuffer);
  69348. // read in each successive scanline
  69349. while (num_scanlines > 0) {
  69350. a = uint8array[dataIndex++];
  69351. b = uint8array[dataIndex++];
  69352. c = uint8array[dataIndex++];
  69353. d = uint8array[dataIndex++];
  69354. if (a != 2 || b != 2 || (c & 0x80)) {
  69355. // this file is not run length encoded
  69356. throw "HDR Bad header format, not RLE";
  69357. }
  69358. if (((c << 8) | d) != scanline_width) {
  69359. throw "HDR Bad header format, wrong scan line width";
  69360. }
  69361. index = 0;
  69362. // read each of the four channels for the scanline into the buffer
  69363. for (i = 0; i < 4; i++) {
  69364. endIndex = (i + 1) * scanline_width;
  69365. while (index < endIndex) {
  69366. a = uint8array[dataIndex++];
  69367. b = uint8array[dataIndex++];
  69368. if (a > 128) {
  69369. // a run of the same value
  69370. count = a - 128;
  69371. if ((count == 0) || (count > endIndex - index)) {
  69372. throw "HDR Bad Format, bad scanline data (run)";
  69373. }
  69374. while (count-- > 0) {
  69375. scanLineArray[index++] = b;
  69376. }
  69377. }
  69378. else {
  69379. // a non-run
  69380. count = a;
  69381. if ((count == 0) || (count > endIndex - index)) {
  69382. throw "HDR Bad Format, bad scanline data (non-run)";
  69383. }
  69384. scanLineArray[index++] = b;
  69385. if (--count > 0) {
  69386. for (var j = 0; j < count; j++) {
  69387. scanLineArray[index++] = uint8array[dataIndex++];
  69388. }
  69389. }
  69390. }
  69391. }
  69392. }
  69393. // now convert data from buffer into floats
  69394. for (i = 0; i < scanline_width; i++) {
  69395. a = scanLineArray[i];
  69396. b = scanLineArray[i + scanline_width];
  69397. c = scanLineArray[i + 2 * scanline_width];
  69398. d = scanLineArray[i + 3 * scanline_width];
  69399. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  69400. }
  69401. num_scanlines--;
  69402. }
  69403. return resultArray;
  69404. };
  69405. return HDRTools;
  69406. }());
  69407. BABYLON.HDRTools = HDRTools;
  69408. })(BABYLON || (BABYLON = {}));
  69409. //# sourceMappingURL=babylon.hdr.js.map
  69410. var BABYLON;
  69411. (function (BABYLON) {
  69412. /**
  69413. * This represents a texture coming from an HDR input.
  69414. *
  69415. * The only supported format is currently panorama picture stored in RGBE format.
  69416. * Example of such files can be found on HDRLib: http://hdrlib.com/
  69417. */
  69418. var HDRCubeTexture = /** @class */ (function (_super) {
  69419. __extends(HDRCubeTexture, _super);
  69420. /**
  69421. * Instantiates an HDRTexture from the following parameters.
  69422. *
  69423. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  69424. * @param scene The scene the texture will be used in
  69425. * @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.
  69426. * @param noMipmap Forces to not generate the mipmap if true
  69427. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  69428. * @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)
  69429. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  69430. */
  69431. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  69432. if (noMipmap === void 0) { noMipmap = false; }
  69433. if (generateHarmonics === void 0) { generateHarmonics = true; }
  69434. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  69435. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  69436. if (onLoad === void 0) { onLoad = null; }
  69437. if (onError === void 0) { onError = null; }
  69438. var _this = _super.call(this, scene) || this;
  69439. _this._useInGammaSpace = false;
  69440. _this._generateHarmonics = true;
  69441. _this._isBABYLONPreprocessed = false;
  69442. _this._onLoad = null;
  69443. _this._onError = null;
  69444. /**
  69445. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  69446. */
  69447. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  69448. /**
  69449. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  69450. * This is usefull at run time to apply the good shader.
  69451. */
  69452. _this.isPMREM = false;
  69453. _this._isBlocking = true;
  69454. if (!url) {
  69455. return _this;
  69456. }
  69457. _this.name = url;
  69458. _this.url = url;
  69459. _this.hasAlpha = false;
  69460. _this.isCube = true;
  69461. _this._textureMatrix = BABYLON.Matrix.Identity();
  69462. _this._onLoad = onLoad;
  69463. _this._onError = onError;
  69464. _this.gammaSpace = false;
  69465. var caps = scene.getEngine().getCaps();
  69466. if (size) {
  69467. _this._isBABYLONPreprocessed = false;
  69468. _this._noMipmap = noMipmap;
  69469. _this._size = size;
  69470. _this._useInGammaSpace = useInGammaSpace;
  69471. _this._usePMREMGenerator = usePMREMGenerator &&
  69472. caps.textureLOD &&
  69473. caps.textureFloat &&
  69474. !_this._useInGammaSpace;
  69475. }
  69476. else {
  69477. _this._isBABYLONPreprocessed = true;
  69478. _this._noMipmap = false;
  69479. _this._useInGammaSpace = false;
  69480. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  69481. !_this._useInGammaSpace;
  69482. }
  69483. _this.isPMREM = _this._usePMREMGenerator;
  69484. _this._texture = _this._getFromCache(url, _this._noMipmap);
  69485. if (!_this._texture) {
  69486. if (!scene.useDelayedTextureLoading) {
  69487. _this.loadTexture();
  69488. }
  69489. else {
  69490. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  69491. }
  69492. }
  69493. return _this;
  69494. }
  69495. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  69496. /**
  69497. * Gets wether or not the texture is blocking during loading.
  69498. */
  69499. get: function () {
  69500. return this._isBlocking;
  69501. },
  69502. /**
  69503. * Sets wether or not the texture is blocking during loading.
  69504. */
  69505. set: function (value) {
  69506. this._isBlocking = value;
  69507. },
  69508. enumerable: true,
  69509. configurable: true
  69510. });
  69511. /**
  69512. * Occurs when the file is a preprocessed .babylon.hdr file.
  69513. */
  69514. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  69515. var _this = this;
  69516. var mipLevels = 0;
  69517. var floatArrayView = null;
  69518. var scene = this.getScene();
  69519. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  69520. var mips = new Array();
  69521. if (!floatArrayView) {
  69522. return mips;
  69523. }
  69524. var startIndex = 30;
  69525. for (var level = 0; level < mipLevels; level++) {
  69526. mips.push([]);
  69527. // Fill each pixel of the mip level.
  69528. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  69529. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  69530. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  69531. mips[level].push(faceData);
  69532. startIndex += faceSize;
  69533. }
  69534. }
  69535. return mips;
  69536. } : null;
  69537. var callback = function (buffer) {
  69538. var scene = _this.getScene();
  69539. if (!scene) {
  69540. return null;
  69541. }
  69542. // Create Native Array Views
  69543. var intArrayView = new Int32Array(buffer);
  69544. floatArrayView = new Float32Array(buffer);
  69545. // Fill header.
  69546. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  69547. _this._size = intArrayView[1]; // CubeMap max mip face size.
  69548. // Update Texture Information.
  69549. if (!_this._texture) {
  69550. return null;
  69551. }
  69552. _this._texture.updateSize(_this._size, _this._size);
  69553. // Fill polynomial information.
  69554. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  69555. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  69556. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  69557. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  69558. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  69559. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  69560. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  69561. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  69562. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  69563. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  69564. _this.sphericalPolynomial = sphericalPolynomial;
  69565. // Fill pixel data.
  69566. mipLevels = intArrayView[29]; // Number of mip levels.
  69567. var startIndex = 30;
  69568. var data = [];
  69569. var faceSize = Math.pow(_this._size, 2) * 3;
  69570. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  69571. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  69572. startIndex += faceSize;
  69573. }
  69574. var results = [];
  69575. var byteArray = null;
  69576. // Push each faces.
  69577. for (var k = 0; k < 6; k++) {
  69578. var dataFace = null;
  69579. // To be deprecated.
  69580. if (version === 1) {
  69581. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  69582. dataFace = data[j];
  69583. }
  69584. // If special cases.
  69585. if (!mipmapGenerator && dataFace) {
  69586. if (!scene.getEngine().getCaps().textureFloat) {
  69587. // 3 channels of 1 bytes per pixel in bytes.
  69588. var byteBuffer = new ArrayBuffer(faceSize);
  69589. byteArray = new Uint8Array(byteBuffer);
  69590. }
  69591. for (var i = 0; i < _this._size * _this._size; i++) {
  69592. // Put in gamma space if requested.
  69593. if (_this._useInGammaSpace) {
  69594. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  69595. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  69596. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  69597. }
  69598. // Convert to int texture for fallback.
  69599. if (byteArray) {
  69600. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  69601. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  69602. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  69603. // May use luminance instead if the result is not accurate.
  69604. var max = Math.max(Math.max(r, g), b);
  69605. if (max > 255) {
  69606. var scale = 255 / max;
  69607. r *= scale;
  69608. g *= scale;
  69609. b *= scale;
  69610. }
  69611. byteArray[(i * 3) + 0] = r;
  69612. byteArray[(i * 3) + 1] = g;
  69613. byteArray[(i * 3) + 2] = b;
  69614. }
  69615. }
  69616. }
  69617. // Fill the array accordingly.
  69618. if (byteArray) {
  69619. results.push(byteArray);
  69620. }
  69621. else {
  69622. results.push(dataFace);
  69623. }
  69624. }
  69625. return results;
  69626. };
  69627. if (scene) {
  69628. 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);
  69629. }
  69630. };
  69631. /**
  69632. * Occurs when the file is raw .hdr file.
  69633. */
  69634. HDRCubeTexture.prototype.loadHDRTexture = function () {
  69635. var _this = this;
  69636. var callback = function (buffer) {
  69637. var scene = _this.getScene();
  69638. if (!scene) {
  69639. return null;
  69640. }
  69641. // Extract the raw linear data.
  69642. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  69643. // Generate harmonics if needed.
  69644. if (_this._generateHarmonics) {
  69645. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  69646. _this.sphericalPolynomial = sphericalPolynomial;
  69647. }
  69648. var results = [];
  69649. var byteArray = null;
  69650. // Push each faces.
  69651. for (var j = 0; j < 6; j++) {
  69652. // Create uintarray fallback.
  69653. if (!scene.getEngine().getCaps().textureFloat) {
  69654. // 3 channels of 1 bytes per pixel in bytes.
  69655. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  69656. byteArray = new Uint8Array(byteBuffer);
  69657. }
  69658. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  69659. // If special cases.
  69660. if (_this._useInGammaSpace || byteArray) {
  69661. for (var i = 0; i < _this._size * _this._size; i++) {
  69662. // Put in gamma space if requested.
  69663. if (_this._useInGammaSpace) {
  69664. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  69665. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  69666. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  69667. }
  69668. // Convert to int texture for fallback.
  69669. if (byteArray) {
  69670. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  69671. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  69672. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  69673. // May use luminance instead if the result is not accurate.
  69674. var max = Math.max(Math.max(r, g), b);
  69675. if (max > 255) {
  69676. var scale = 255 / max;
  69677. r *= scale;
  69678. g *= scale;
  69679. b *= scale;
  69680. }
  69681. byteArray[(i * 3) + 0] = r;
  69682. byteArray[(i * 3) + 1] = g;
  69683. byteArray[(i * 3) + 2] = b;
  69684. }
  69685. }
  69686. }
  69687. if (byteArray) {
  69688. results.push(byteArray);
  69689. }
  69690. else {
  69691. results.push(dataFace);
  69692. }
  69693. }
  69694. return results;
  69695. };
  69696. var mipmapGenerator = null;
  69697. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  69698. // if (!this._noMipmap &&
  69699. // this._usePMREMGenerator) {
  69700. // mipmapGenerator = (data: ArrayBufferView[]) => {
  69701. // // Custom setup of the generator matching with the PBR shader values.
  69702. // var generator = new BABYLON.PMREMGenerator(data,
  69703. // this._size,
  69704. // this._size,
  69705. // 0,
  69706. // 3,
  69707. // this.getScene().getEngine().getCaps().textureFloat,
  69708. // 2048,
  69709. // 0.25,
  69710. // false,
  69711. // true);
  69712. // return generator.filterCubeMap();
  69713. // };
  69714. // }
  69715. var scene = this.getScene();
  69716. if (scene) {
  69717. 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);
  69718. }
  69719. };
  69720. /**
  69721. * Starts the loading process of the texture.
  69722. */
  69723. HDRCubeTexture.prototype.loadTexture = function () {
  69724. if (this._isBABYLONPreprocessed) {
  69725. this.loadBabylonTexture();
  69726. }
  69727. else {
  69728. this.loadHDRTexture();
  69729. }
  69730. };
  69731. HDRCubeTexture.prototype.clone = function () {
  69732. var scene = this.getScene();
  69733. if (!scene) {
  69734. return this;
  69735. }
  69736. var size = (this._isBABYLONPreprocessed ? null : this._size);
  69737. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  69738. // Base texture
  69739. newTexture.level = this.level;
  69740. newTexture.wrapU = this.wrapU;
  69741. newTexture.wrapV = this.wrapV;
  69742. newTexture.coordinatesIndex = this.coordinatesIndex;
  69743. newTexture.coordinatesMode = this.coordinatesMode;
  69744. return newTexture;
  69745. };
  69746. // Methods
  69747. HDRCubeTexture.prototype.delayLoad = function () {
  69748. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69749. return;
  69750. }
  69751. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69752. this._texture = this._getFromCache(this.url, this._noMipmap);
  69753. if (!this._texture) {
  69754. this.loadTexture();
  69755. }
  69756. };
  69757. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  69758. return this._textureMatrix;
  69759. };
  69760. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69761. this._textureMatrix = value;
  69762. };
  69763. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69764. var texture = null;
  69765. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  69766. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  69767. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  69768. texture.name = parsedTexture.name;
  69769. texture.hasAlpha = parsedTexture.hasAlpha;
  69770. texture.level = parsedTexture.level;
  69771. texture.coordinatesMode = parsedTexture.coordinatesMode;
  69772. texture.isBlocking = parsedTexture.isBlocking;
  69773. }
  69774. return texture;
  69775. };
  69776. HDRCubeTexture.prototype.serialize = function () {
  69777. if (!this.name) {
  69778. return null;
  69779. }
  69780. var serializationObject = {};
  69781. serializationObject.name = this.name;
  69782. serializationObject.hasAlpha = this.hasAlpha;
  69783. serializationObject.isCube = true;
  69784. serializationObject.level = this.level;
  69785. serializationObject.size = this._size;
  69786. serializationObject.coordinatesMode = this.coordinatesMode;
  69787. serializationObject.useInGammaSpace = this._useInGammaSpace;
  69788. serializationObject.generateHarmonics = this._generateHarmonics;
  69789. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  69790. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  69791. serializationObject.customType = "BABYLON.HDRCubeTexture";
  69792. serializationObject.noMipmap = this._noMipmap;
  69793. serializationObject.isBlocking = this._isBlocking;
  69794. return serializationObject;
  69795. };
  69796. /**
  69797. * Saves as a file the data contained in the texture in a binary format.
  69798. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69799. * as the spherical used in the lighting.
  69800. * @param url The HDR file url.
  69801. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69802. * @param onError Method called if any error happens during download.
  69803. * @return The packed binary data.
  69804. */
  69805. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  69806. if (onError === void 0) { onError = null; }
  69807. var callback = function (buffer) {
  69808. var data = new Blob([buffer], { type: 'application/octet-stream' });
  69809. // Returns a URL you can use as a href.
  69810. var objUrl = window.URL.createObjectURL(data);
  69811. // Simulates a link to it and click to dowload.
  69812. var a = document.createElement("a");
  69813. document.body.appendChild(a);
  69814. a.style.display = "none";
  69815. a.href = objUrl;
  69816. a.download = "envmap.babylon.hdr";
  69817. a.click();
  69818. };
  69819. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  69820. };
  69821. /**
  69822. * Serializes the data contained in the texture in a binary format.
  69823. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69824. * as the spherical used in the lighting.
  69825. * @param url The HDR file url.
  69826. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69827. * @param onError Method called if any error happens during download.
  69828. * @return The packed binary data.
  69829. */
  69830. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  69831. if (onError === void 0) { onError = null; }
  69832. // Needs the url tho create the texture.
  69833. if (!url) {
  69834. return;
  69835. }
  69836. // Check Power of two size.
  69837. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  69838. return;
  69839. }
  69840. // Coming Back in 3.x.
  69841. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  69842. };
  69843. HDRCubeTexture._facesMapping = [
  69844. "right",
  69845. "left",
  69846. "up",
  69847. "down",
  69848. "front",
  69849. "back"
  69850. ];
  69851. return HDRCubeTexture;
  69852. }(BABYLON.BaseTexture));
  69853. BABYLON.HDRCubeTexture = HDRCubeTexture;
  69854. })(BABYLON || (BABYLON = {}));
  69855. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  69856. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  69857. // Huge respect for a such great lib.
  69858. // Earcut license:
  69859. // Copyright (c) 2016, Mapbox
  69860. //
  69861. // Permission to use, copy, modify, and/or distribute this software for any purpose
  69862. // with or without fee is hereby granted, provided that the above copyright notice
  69863. // and this permission notice appear in all copies.
  69864. //
  69865. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  69866. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  69867. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  69868. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  69869. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  69870. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  69871. // THIS SOFTWARE.
  69872. var Earcut;
  69873. (function (Earcut) {
  69874. /**
  69875. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  69876. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  69877. * @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).
  69878. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  69879. */
  69880. function earcut(data, holeIndices, dim) {
  69881. dim = dim || 2;
  69882. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  69883. if (!outerNode)
  69884. return triangles;
  69885. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  69886. if (hasHoles)
  69887. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  69888. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  69889. if (data.length > 80 * dim) {
  69890. minX = maxX = data[0];
  69891. minY = maxY = data[1];
  69892. for (var i = dim; i < outerLen; i += dim) {
  69893. x = data[i];
  69894. y = data[i + 1];
  69895. if (x < minX)
  69896. minX = x;
  69897. if (y < minY)
  69898. minY = y;
  69899. if (x > maxX)
  69900. maxX = x;
  69901. if (y > maxY)
  69902. maxY = y;
  69903. }
  69904. // minX, minY and size are later used to transform coords into integers for z-order calculation
  69905. size = Math.max(maxX - minX, maxY - minY);
  69906. }
  69907. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  69908. return triangles;
  69909. }
  69910. Earcut.earcut = earcut;
  69911. var Node = /** @class */ (function () {
  69912. function Node(i, x, y) {
  69913. this.i = i;
  69914. this.x = x;
  69915. this.y = y;
  69916. this.prev = null;
  69917. this.next = null;
  69918. this.z = null;
  69919. this.prevZ = null;
  69920. this.nextZ = null;
  69921. this.steiner = false;
  69922. }
  69923. return Node;
  69924. }());
  69925. // create a circular doubly linked list from polygon points in the specified winding order
  69926. function linkedList(data, start, end, dim, clockwise) {
  69927. var i, last = null;
  69928. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  69929. for (i = start; i < end; i += dim)
  69930. last = insertNode(i, data[i], data[i + 1], last);
  69931. }
  69932. else {
  69933. for (i = end - dim; i >= start; i -= dim)
  69934. last = insertNode(i, data[i], data[i + 1], last);
  69935. }
  69936. if (last && equals(last, last.next)) {
  69937. removeNode(last);
  69938. last = last.next;
  69939. }
  69940. return last;
  69941. }
  69942. // eliminate colinear or duplicate points
  69943. function filterPoints(start, end) {
  69944. if (!start)
  69945. return start;
  69946. if (!end)
  69947. end = start;
  69948. var p = start, again;
  69949. do {
  69950. again = false;
  69951. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  69952. removeNode(p);
  69953. p = end = p.prev;
  69954. if (p === p.next)
  69955. return undefined;
  69956. again = true;
  69957. }
  69958. else {
  69959. p = p.next;
  69960. }
  69961. } while (again || p !== end);
  69962. return end;
  69963. }
  69964. // main ear slicing loop which triangulates a polygon (given as a linked list)
  69965. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  69966. if (!ear)
  69967. return;
  69968. // interlink polygon nodes in z-order
  69969. if (!pass && size)
  69970. indexCurve(ear, minX, minY, size);
  69971. var stop = ear, prev, next;
  69972. // iterate through ears, slicing them one by one
  69973. while (ear.prev !== ear.next) {
  69974. prev = ear.prev;
  69975. next = ear.next;
  69976. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  69977. // cut off the triangle
  69978. triangles.push(prev.i / dim);
  69979. triangles.push(ear.i / dim);
  69980. triangles.push(next.i / dim);
  69981. removeNode(ear);
  69982. // skipping the next vertice leads to less sliver triangles
  69983. ear = next.next;
  69984. stop = next.next;
  69985. continue;
  69986. }
  69987. ear = next;
  69988. // if we looped through the whole remaining polygon and can't find any more ears
  69989. if (ear === stop) {
  69990. // try filtering points and slicing again
  69991. if (!pass) {
  69992. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  69993. // if this didn't work, try curing all small self-intersections locally
  69994. }
  69995. else if (pass === 1) {
  69996. ear = cureLocalIntersections(ear, triangles, dim);
  69997. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  69998. // as a last resort, try splitting the remaining polygon into two
  69999. }
  70000. else if (pass === 2) {
  70001. splitEarcut(ear, triangles, dim, minX, minY, size);
  70002. }
  70003. break;
  70004. }
  70005. }
  70006. }
  70007. // check whether a polygon node forms a valid ear with adjacent nodes
  70008. function isEar(ear) {
  70009. var a = ear.prev, b = ear, c = ear.next;
  70010. if (area(a, b, c) >= 0)
  70011. return false; // reflex, can't be an ear
  70012. // now make sure we don't have other points inside the potential ear
  70013. var p = ear.next.next;
  70014. while (p !== ear.prev) {
  70015. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  70016. area(p.prev, p, p.next) >= 0)
  70017. return false;
  70018. p = p.next;
  70019. }
  70020. return true;
  70021. }
  70022. function isEarHashed(ear, minX, minY, size) {
  70023. var a = ear.prev, b = ear, c = ear.next;
  70024. if (area(a, b, c) >= 0)
  70025. return false; // reflex, can't be an ear
  70026. // triangle bbox; min & max are calculated like this for speed
  70027. 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);
  70028. // z-order range for the current triangle bbox;
  70029. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  70030. // first look for points inside the triangle in increasing z-order
  70031. var p = ear.nextZ;
  70032. while (p && p.z <= maxZ) {
  70033. if (p !== ear.prev &&
  70034. p !== ear.next &&
  70035. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  70036. area(p.prev, p, p.next) >= 0)
  70037. return false;
  70038. p = p.nextZ;
  70039. }
  70040. // then look for points in decreasing z-order
  70041. p = ear.prevZ;
  70042. while (p && p.z >= minZ) {
  70043. if (p !== ear.prev &&
  70044. p !== ear.next &&
  70045. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  70046. area(p.prev, p, p.next) >= 0)
  70047. return false;
  70048. p = p.prevZ;
  70049. }
  70050. return true;
  70051. }
  70052. // go through all polygon nodes and cure small local self-intersections
  70053. function cureLocalIntersections(start, triangles, dim) {
  70054. var p = start;
  70055. do {
  70056. var a = p.prev, b = p.next.next;
  70057. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  70058. triangles.push(a.i / dim);
  70059. triangles.push(p.i / dim);
  70060. triangles.push(b.i / dim);
  70061. // remove two nodes involved
  70062. removeNode(p);
  70063. removeNode(p.next);
  70064. p = start = b;
  70065. }
  70066. p = p.next;
  70067. } while (p !== start);
  70068. return p;
  70069. }
  70070. // try splitting polygon into two and triangulate them independently
  70071. function splitEarcut(start, triangles, dim, minX, minY, size) {
  70072. // look for a valid diagonal that divides the polygon into two
  70073. var a = start;
  70074. do {
  70075. var b = a.next.next;
  70076. while (b !== a.prev) {
  70077. if (a.i !== b.i && isValidDiagonal(a, b)) {
  70078. // split the polygon in two by the diagonal
  70079. var c = splitPolygon(a, b);
  70080. // filter colinear points around the cuts
  70081. a = filterPoints(a, a.next);
  70082. c = filterPoints(c, c.next);
  70083. // run earcut on each half
  70084. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  70085. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  70086. return;
  70087. }
  70088. b = b.next;
  70089. }
  70090. a = a.next;
  70091. } while (a !== start);
  70092. }
  70093. // link every hole into the outer loop, producing a single-ring polygon without holes
  70094. function eliminateHoles(data, holeIndices, outerNode, dim) {
  70095. var queue = [], i, len, start, end, list;
  70096. for (i = 0, len = holeIndices.length; i < len; i++) {
  70097. start = holeIndices[i] * dim;
  70098. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  70099. list = linkedList(data, start, end, dim, false);
  70100. if (list === list.next)
  70101. list.steiner = true;
  70102. queue.push(getLeftmost(list));
  70103. }
  70104. queue.sort(compareX);
  70105. // process holes from left to right
  70106. for (i = 0; i < queue.length; i++) {
  70107. eliminateHole(queue[i], outerNode);
  70108. outerNode = filterPoints(outerNode, outerNode.next);
  70109. }
  70110. return outerNode;
  70111. }
  70112. function compareX(a, b) {
  70113. return a.x - b.x;
  70114. }
  70115. // find a bridge between vertices that connects hole with an outer ring and and link it
  70116. function eliminateHole(hole, outerNode) {
  70117. outerNode = findHoleBridge(hole, outerNode);
  70118. if (outerNode) {
  70119. var b = splitPolygon(outerNode, hole);
  70120. filterPoints(b, b.next);
  70121. }
  70122. }
  70123. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  70124. function findHoleBridge(hole, outerNode) {
  70125. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  70126. // find a segment intersected by a ray from the hole's leftmost point to the left;
  70127. // segment's endpoint with lesser x will be potential connection point
  70128. do {
  70129. if (hy <= p.y && hy >= p.next.y) {
  70130. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  70131. if (x <= hx && x > qx) {
  70132. qx = x;
  70133. if (x === hx) {
  70134. if (hy === p.y)
  70135. return p;
  70136. if (hy === p.next.y)
  70137. return p.next;
  70138. }
  70139. m = p.x < p.next.x ? p : p.next;
  70140. }
  70141. }
  70142. p = p.next;
  70143. } while (p !== outerNode);
  70144. if (!m)
  70145. return null;
  70146. if (hx === qx)
  70147. return m.prev; // hole touches outer segment; pick lower endpoint
  70148. // look for points inside the triangle of hole point, segment intersection and endpoint;
  70149. // if there are no points found, we have a valid connection;
  70150. // otherwise choose the point of the minimum angle with the ray as connection point
  70151. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  70152. p = m.next;
  70153. while (p !== stop) {
  70154. if (hx >= p.x &&
  70155. p.x >= mx &&
  70156. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  70157. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  70158. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  70159. m = p;
  70160. tanMin = tan;
  70161. }
  70162. }
  70163. p = p.next;
  70164. }
  70165. return m;
  70166. }
  70167. // interlink polygon nodes in z-order
  70168. function indexCurve(start, minX, minY, size) {
  70169. var p = start;
  70170. do {
  70171. if (p.z === null)
  70172. p.z = zOrder(p.x, p.y, minX, minY, size);
  70173. p.prevZ = p.prev;
  70174. p.nextZ = p.next;
  70175. p = p.next;
  70176. } while (p !== start);
  70177. p.prevZ.nextZ = null;
  70178. p.prevZ = null;
  70179. sortLinked(p);
  70180. }
  70181. // Simon Tatham's linked list merge sort algorithm
  70182. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  70183. function sortLinked(list) {
  70184. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  70185. do {
  70186. p = list;
  70187. list = null;
  70188. tail = null;
  70189. numMerges = 0;
  70190. while (p) {
  70191. numMerges++;
  70192. q = p;
  70193. pSize = 0;
  70194. for (i = 0; i < inSize; i++) {
  70195. pSize++;
  70196. q = q.nextZ;
  70197. if (!q)
  70198. break;
  70199. }
  70200. qSize = inSize;
  70201. while (pSize > 0 || (qSize > 0 && q)) {
  70202. if (pSize === 0) {
  70203. e = q;
  70204. q = q.nextZ;
  70205. qSize--;
  70206. }
  70207. else if (qSize === 0 || !q) {
  70208. e = p;
  70209. p = p.nextZ;
  70210. pSize--;
  70211. }
  70212. else if (p.z <= q.z) {
  70213. e = p;
  70214. p = p.nextZ;
  70215. pSize--;
  70216. }
  70217. else {
  70218. e = q;
  70219. q = q.nextZ;
  70220. qSize--;
  70221. }
  70222. if (tail)
  70223. tail.nextZ = e;
  70224. else
  70225. list = e;
  70226. e.prevZ = tail;
  70227. tail = e;
  70228. }
  70229. p = q;
  70230. }
  70231. tail.nextZ = null;
  70232. inSize *= 2;
  70233. } while (numMerges > 1);
  70234. return list;
  70235. }
  70236. // z-order of a point given coords and size of the data bounding box
  70237. function zOrder(x, y, minX, minY, size) {
  70238. // coords are transformed into non-negative 15-bit integer range
  70239. x = 32767 * (x - minX) / size;
  70240. y = 32767 * (y - minY) / size;
  70241. x = (x | (x << 8)) & 0x00FF00FF;
  70242. x = (x | (x << 4)) & 0x0F0F0F0F;
  70243. x = (x | (x << 2)) & 0x33333333;
  70244. x = (x | (x << 1)) & 0x55555555;
  70245. y = (y | (y << 8)) & 0x00FF00FF;
  70246. y = (y | (y << 4)) & 0x0F0F0F0F;
  70247. y = (y | (y << 2)) & 0x33333333;
  70248. y = (y | (y << 1)) & 0x55555555;
  70249. return x | (y << 1);
  70250. }
  70251. // find the leftmost node of a polygon ring
  70252. function getLeftmost(start) {
  70253. var p = start, leftmost = start;
  70254. do {
  70255. if (p.x < leftmost.x)
  70256. leftmost = p;
  70257. p = p.next;
  70258. } while (p !== start);
  70259. return leftmost;
  70260. }
  70261. // check if a point lies within a convex triangle
  70262. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  70263. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  70264. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  70265. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  70266. }
  70267. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  70268. function isValidDiagonal(a, b) {
  70269. return a.next.i !== b.i &&
  70270. a.prev.i !== b.i &&
  70271. !intersectsPolygon(a, b) &&
  70272. locallyInside(a, b) &&
  70273. locallyInside(b, a) &&
  70274. middleInside(a, b);
  70275. }
  70276. // signed area of a triangle
  70277. function area(p, q, r) {
  70278. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  70279. }
  70280. // check if two points are equal
  70281. function equals(p1, p2) {
  70282. return p1.x === p2.x && p1.y === p2.y;
  70283. }
  70284. // check if two segments intersect
  70285. function intersects(p1, q1, p2, q2) {
  70286. if ((equals(p1, q1) && equals(p2, q2)) ||
  70287. (equals(p1, q2) && equals(p2, q1)))
  70288. return true;
  70289. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  70290. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  70291. }
  70292. // check if a polygon diagonal intersects any polygon segments
  70293. function intersectsPolygon(a, b) {
  70294. var p = a;
  70295. do {
  70296. if (p.i !== a.i &&
  70297. p.next.i !== a.i &&
  70298. p.i !== b.i &&
  70299. p.next.i !== b.i &&
  70300. intersects(p, p.next, a, b))
  70301. return true;
  70302. p = p.next;
  70303. } while (p !== a);
  70304. return false;
  70305. }
  70306. // check if a polygon diagonal is locally inside the polygon
  70307. function locallyInside(a, b) {
  70308. return area(a.prev, a, a.next) < 0
  70309. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  70310. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  70311. }
  70312. // check if the middle point of a polygon diagonal is inside the polygon
  70313. function middleInside(a, b) {
  70314. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  70315. do {
  70316. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  70317. inside = !inside;
  70318. p = p.next;
  70319. } while (p !== a);
  70320. return inside;
  70321. }
  70322. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  70323. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  70324. function splitPolygon(a, b) {
  70325. 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;
  70326. a.next = b;
  70327. b.prev = a;
  70328. a2.next = an;
  70329. an.prev = a2;
  70330. b2.next = a2;
  70331. a2.prev = b2;
  70332. bp.next = b2;
  70333. b2.prev = bp;
  70334. return b2;
  70335. }
  70336. // create a node and optionally link it with previous one (in a circular doubly linked list)
  70337. function insertNode(i, x, y, last) {
  70338. var p = new Node(i, x, y);
  70339. if (!last) {
  70340. p.prev = p;
  70341. p.next = p;
  70342. }
  70343. else {
  70344. p.next = last.next;
  70345. p.prev = last;
  70346. last.next.prev = p;
  70347. last.next = p;
  70348. }
  70349. return p;
  70350. }
  70351. function removeNode(p) {
  70352. p.next.prev = p.prev;
  70353. p.prev.next = p.next;
  70354. if (p.prevZ)
  70355. p.prevZ.nextZ = p.nextZ;
  70356. if (p.nextZ)
  70357. p.nextZ.prevZ = p.prevZ;
  70358. }
  70359. /**
  70360. * return a percentage difference between the polygon area and its triangulation area;
  70361. * used to verify correctness of triangulation
  70362. */
  70363. function deviation(data, holeIndices, dim, triangles) {
  70364. var hasHoles = holeIndices && holeIndices.length;
  70365. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  70366. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  70367. if (hasHoles) {
  70368. for (var i = 0, len = holeIndices.length; i < len; i++) {
  70369. var start = holeIndices[i] * dim;
  70370. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  70371. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  70372. }
  70373. }
  70374. var trianglesArea = 0;
  70375. for (i = 0; i < triangles.length; i += 3) {
  70376. var a = triangles[i] * dim;
  70377. var b = triangles[i + 1] * dim;
  70378. var c = triangles[i + 2] * dim;
  70379. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  70380. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  70381. }
  70382. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  70383. }
  70384. Earcut.deviation = deviation;
  70385. ;
  70386. function signedArea(data, start, end, dim) {
  70387. var sum = 0;
  70388. for (var i = start, j = end - dim; i < end; i += dim) {
  70389. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  70390. j = i;
  70391. }
  70392. return sum;
  70393. }
  70394. /**
  70395. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  70396. */
  70397. function flatten(data) {
  70398. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  70399. for (var i = 0; i < data.length; i++) {
  70400. for (var j = 0; j < data[i].length; j++) {
  70401. for (var d = 0; d < dim; d++)
  70402. result.vertices.push(data[i][j][d]);
  70403. }
  70404. if (i > 0) {
  70405. holeIndex += data[i - 1].length;
  70406. result.holes.push(holeIndex);
  70407. }
  70408. }
  70409. return result;
  70410. }
  70411. Earcut.flatten = flatten;
  70412. ;
  70413. })(Earcut || (Earcut = {}));
  70414. //# sourceMappingURL=babylon.earcut.js.map
  70415. var BABYLON;
  70416. (function (BABYLON) {
  70417. var IndexedVector2 = /** @class */ (function (_super) {
  70418. __extends(IndexedVector2, _super);
  70419. function IndexedVector2(original, index) {
  70420. var _this = _super.call(this, original.x, original.y) || this;
  70421. _this.index = index;
  70422. return _this;
  70423. }
  70424. return IndexedVector2;
  70425. }(BABYLON.Vector2));
  70426. var PolygonPoints = /** @class */ (function () {
  70427. function PolygonPoints() {
  70428. this.elements = new Array();
  70429. }
  70430. PolygonPoints.prototype.add = function (originalPoints) {
  70431. var _this = this;
  70432. var result = new Array();
  70433. originalPoints.forEach(function (point) {
  70434. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  70435. var newPoint = new IndexedVector2(point, _this.elements.length);
  70436. result.push(newPoint);
  70437. _this.elements.push(newPoint);
  70438. }
  70439. });
  70440. return result;
  70441. };
  70442. PolygonPoints.prototype.computeBounds = function () {
  70443. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  70444. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  70445. this.elements.forEach(function (point) {
  70446. // x
  70447. if (point.x < lmin.x) {
  70448. lmin.x = point.x;
  70449. }
  70450. else if (point.x > lmax.x) {
  70451. lmax.x = point.x;
  70452. }
  70453. // y
  70454. if (point.y < lmin.y) {
  70455. lmin.y = point.y;
  70456. }
  70457. else if (point.y > lmax.y) {
  70458. lmax.y = point.y;
  70459. }
  70460. });
  70461. return {
  70462. min: lmin,
  70463. max: lmax,
  70464. width: lmax.x - lmin.x,
  70465. height: lmax.y - lmin.y
  70466. };
  70467. };
  70468. return PolygonPoints;
  70469. }());
  70470. var Polygon = /** @class */ (function () {
  70471. function Polygon() {
  70472. }
  70473. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  70474. return [
  70475. new BABYLON.Vector2(xmin, ymin),
  70476. new BABYLON.Vector2(xmax, ymin),
  70477. new BABYLON.Vector2(xmax, ymax),
  70478. new BABYLON.Vector2(xmin, ymax)
  70479. ];
  70480. };
  70481. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  70482. if (cx === void 0) { cx = 0; }
  70483. if (cy === void 0) { cy = 0; }
  70484. if (numberOfSides === void 0) { numberOfSides = 32; }
  70485. var result = new Array();
  70486. var angle = 0;
  70487. var increment = (Math.PI * 2) / numberOfSides;
  70488. for (var i = 0; i < numberOfSides; i++) {
  70489. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  70490. angle -= increment;
  70491. }
  70492. return result;
  70493. };
  70494. Polygon.Parse = function (input) {
  70495. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  70496. var i, result = [];
  70497. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  70498. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  70499. }
  70500. return result;
  70501. };
  70502. Polygon.StartingAt = function (x, y) {
  70503. return BABYLON.Path2.StartingAt(x, y);
  70504. };
  70505. return Polygon;
  70506. }());
  70507. BABYLON.Polygon = Polygon;
  70508. var PolygonMeshBuilder = /** @class */ (function () {
  70509. function PolygonMeshBuilder(name, contours, scene) {
  70510. this._points = new PolygonPoints();
  70511. this._outlinepoints = new PolygonPoints();
  70512. this._holes = new Array();
  70513. this._epoints = new Array();
  70514. this._eholes = new Array();
  70515. this._name = name;
  70516. this._scene = scene;
  70517. var points;
  70518. if (contours instanceof BABYLON.Path2) {
  70519. points = contours.getPoints();
  70520. }
  70521. else {
  70522. points = contours;
  70523. }
  70524. this._addToepoint(points);
  70525. this._points.add(points);
  70526. this._outlinepoints.add(points);
  70527. }
  70528. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  70529. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  70530. var p = points_1[_i];
  70531. this._epoints.push(p.x, p.y);
  70532. }
  70533. };
  70534. PolygonMeshBuilder.prototype.addHole = function (hole) {
  70535. this._points.add(hole);
  70536. var holepoints = new PolygonPoints();
  70537. holepoints.add(hole);
  70538. this._holes.push(holepoints);
  70539. this._eholes.push(this._epoints.length / 2);
  70540. this._addToepoint(hole);
  70541. return this;
  70542. };
  70543. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  70544. var _this = this;
  70545. if (updatable === void 0) { updatable = false; }
  70546. if (depth === void 0) { depth = 0; }
  70547. var result = new BABYLON.Mesh(this._name, this._scene);
  70548. var normals = new Array();
  70549. var positions = new Array();
  70550. var uvs = new Array();
  70551. var bounds = this._points.computeBounds();
  70552. this._points.elements.forEach(function (p) {
  70553. normals.push(0, 1.0, 0);
  70554. positions.push(p.x, 0, p.y);
  70555. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  70556. });
  70557. var indices = new Array();
  70558. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  70559. for (var i = 0; i < res.length; i++) {
  70560. indices.push(res[i]);
  70561. }
  70562. if (depth > 0) {
  70563. var positionscount = (positions.length / 3); //get the current pointcount
  70564. this._points.elements.forEach(function (p) {
  70565. normals.push(0, -1.0, 0);
  70566. positions.push(p.x, -depth, p.y);
  70567. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  70568. });
  70569. var totalCount = indices.length;
  70570. for (var i = 0; i < totalCount; i += 3) {
  70571. var i0 = indices[i + 0];
  70572. var i1 = indices[i + 1];
  70573. var i2 = indices[i + 2];
  70574. indices.push(i2 + positionscount);
  70575. indices.push(i1 + positionscount);
  70576. indices.push(i0 + positionscount);
  70577. }
  70578. //Add the sides
  70579. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  70580. this._holes.forEach(function (hole) {
  70581. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  70582. });
  70583. }
  70584. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  70585. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  70586. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  70587. result.setIndices(indices);
  70588. return result;
  70589. };
  70590. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  70591. var StartIndex = positions.length / 3;
  70592. var ulength = 0;
  70593. for (var i = 0; i < points.elements.length; i++) {
  70594. var p = points.elements[i];
  70595. var p1;
  70596. if ((i + 1) > points.elements.length - 1) {
  70597. p1 = points.elements[0];
  70598. }
  70599. else {
  70600. p1 = points.elements[i + 1];
  70601. }
  70602. positions.push(p.x, 0, p.y);
  70603. positions.push(p.x, -depth, p.y);
  70604. positions.push(p1.x, 0, p1.y);
  70605. positions.push(p1.x, -depth, p1.y);
  70606. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  70607. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  70608. var v3 = v2.subtract(v1);
  70609. var v4 = new BABYLON.Vector3(0, 1, 0);
  70610. var vn = BABYLON.Vector3.Cross(v3, v4);
  70611. vn = vn.normalize();
  70612. uvs.push(ulength / bounds.width, 0);
  70613. uvs.push(ulength / bounds.width, 1);
  70614. ulength += v3.length();
  70615. uvs.push((ulength / bounds.width), 0);
  70616. uvs.push((ulength / bounds.width), 1);
  70617. if (!flip) {
  70618. normals.push(-vn.x, -vn.y, -vn.z);
  70619. normals.push(-vn.x, -vn.y, -vn.z);
  70620. normals.push(-vn.x, -vn.y, -vn.z);
  70621. normals.push(-vn.x, -vn.y, -vn.z);
  70622. indices.push(StartIndex);
  70623. indices.push(StartIndex + 1);
  70624. indices.push(StartIndex + 2);
  70625. indices.push(StartIndex + 1);
  70626. indices.push(StartIndex + 3);
  70627. indices.push(StartIndex + 2);
  70628. }
  70629. else {
  70630. normals.push(vn.x, vn.y, vn.z);
  70631. normals.push(vn.x, vn.y, vn.z);
  70632. normals.push(vn.x, vn.y, vn.z);
  70633. normals.push(vn.x, vn.y, vn.z);
  70634. indices.push(StartIndex);
  70635. indices.push(StartIndex + 2);
  70636. indices.push(StartIndex + 1);
  70637. indices.push(StartIndex + 1);
  70638. indices.push(StartIndex + 2);
  70639. indices.push(StartIndex + 3);
  70640. }
  70641. StartIndex += 4;
  70642. }
  70643. ;
  70644. };
  70645. return PolygonMeshBuilder;
  70646. }());
  70647. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  70648. })(BABYLON || (BABYLON = {}));
  70649. //# sourceMappingURL=babylon.polygonMesh.js.map
  70650. var BABYLON;
  70651. (function (BABYLON) {
  70652. // Unique ID when we import meshes from Babylon to CSG
  70653. var currentCSGMeshId = 0;
  70654. // # class Vertex
  70655. // Represents a vertex of a polygon. Use your own vertex class instead of this
  70656. // one to provide additional features like texture coordinates and vertex
  70657. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  70658. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  70659. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  70660. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  70661. // is not used anywhere else.
  70662. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  70663. var Vertex = /** @class */ (function () {
  70664. function Vertex(pos, normal, uv) {
  70665. this.pos = pos;
  70666. this.normal = normal;
  70667. this.uv = uv;
  70668. }
  70669. Vertex.prototype.clone = function () {
  70670. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  70671. };
  70672. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  70673. // orientation of a polygon is flipped.
  70674. Vertex.prototype.flip = function () {
  70675. this.normal = this.normal.scale(-1);
  70676. };
  70677. // Create a new vertex between this vertex and `other` by linearly
  70678. // interpolating all properties using a parameter of `t`. Subclasses should
  70679. // override this to interpolate additional properties.
  70680. Vertex.prototype.interpolate = function (other, t) {
  70681. 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));
  70682. };
  70683. return Vertex;
  70684. }());
  70685. // # class Plane
  70686. // Represents a plane in 3D space.
  70687. var Plane = /** @class */ (function () {
  70688. function Plane(normal, w) {
  70689. this.normal = normal;
  70690. this.w = w;
  70691. }
  70692. Plane.FromPoints = function (a, b, c) {
  70693. var v0 = c.subtract(a);
  70694. var v1 = b.subtract(a);
  70695. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  70696. return null;
  70697. }
  70698. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  70699. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  70700. };
  70701. Plane.prototype.clone = function () {
  70702. return new Plane(this.normal.clone(), this.w);
  70703. };
  70704. Plane.prototype.flip = function () {
  70705. this.normal.scaleInPlace(-1);
  70706. this.w = -this.w;
  70707. };
  70708. // Split `polygon` by this plane if needed, then put the polygon or polygon
  70709. // fragments in the appropriate lists. Coplanar polygons go into either
  70710. // `coplanarFront` or `coplanarBack` depending on their orientation with
  70711. // respect to this plane. Polygons in front or in back of this plane go into
  70712. // either `front` or `back`.
  70713. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  70714. var COPLANAR = 0;
  70715. var FRONT = 1;
  70716. var BACK = 2;
  70717. var SPANNING = 3;
  70718. // Classify each point as well as the entire polygon into one of the above
  70719. // four classes.
  70720. var polygonType = 0;
  70721. var types = [];
  70722. var i;
  70723. var t;
  70724. for (i = 0; i < polygon.vertices.length; i++) {
  70725. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  70726. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  70727. polygonType |= type;
  70728. types.push(type);
  70729. }
  70730. // Put the polygon in the correct list, splitting it when necessary.
  70731. switch (polygonType) {
  70732. case COPLANAR:
  70733. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  70734. break;
  70735. case FRONT:
  70736. front.push(polygon);
  70737. break;
  70738. case BACK:
  70739. back.push(polygon);
  70740. break;
  70741. case SPANNING:
  70742. var f = [], b = [];
  70743. for (i = 0; i < polygon.vertices.length; i++) {
  70744. var j = (i + 1) % polygon.vertices.length;
  70745. var ti = types[i], tj = types[j];
  70746. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  70747. if (ti !== BACK)
  70748. f.push(vi);
  70749. if (ti !== FRONT)
  70750. b.push(ti !== BACK ? vi.clone() : vi);
  70751. if ((ti | tj) === SPANNING) {
  70752. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  70753. var v = vi.interpolate(vj, t);
  70754. f.push(v);
  70755. b.push(v.clone());
  70756. }
  70757. }
  70758. var poly;
  70759. if (f.length >= 3) {
  70760. poly = new Polygon(f, polygon.shared);
  70761. if (poly.plane)
  70762. front.push(poly);
  70763. }
  70764. if (b.length >= 3) {
  70765. poly = new Polygon(b, polygon.shared);
  70766. if (poly.plane)
  70767. back.push(poly);
  70768. }
  70769. break;
  70770. }
  70771. };
  70772. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  70773. // point is on the plane.
  70774. Plane.EPSILON = 1e-5;
  70775. return Plane;
  70776. }());
  70777. // # class Polygon
  70778. // Represents a convex polygon. The vertices used to initialize a polygon must
  70779. // be coplanar and form a convex loop.
  70780. //
  70781. // Each convex polygon has a `shared` property, which is shared between all
  70782. // polygons that are clones of each other or were split from the same polygon.
  70783. // This can be used to define per-polygon properties (such as surface color).
  70784. var Polygon = /** @class */ (function () {
  70785. function Polygon(vertices, shared) {
  70786. this.vertices = vertices;
  70787. this.shared = shared;
  70788. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  70789. }
  70790. Polygon.prototype.clone = function () {
  70791. var vertices = this.vertices.map(function (v) { return v.clone(); });
  70792. return new Polygon(vertices, this.shared);
  70793. };
  70794. Polygon.prototype.flip = function () {
  70795. this.vertices.reverse().map(function (v) { v.flip(); });
  70796. this.plane.flip();
  70797. };
  70798. return Polygon;
  70799. }());
  70800. // # class Node
  70801. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  70802. // by picking a polygon to split along. That polygon (and all other coplanar
  70803. // polygons) are added directly to that node and the other polygons are added to
  70804. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  70805. // no distinction between internal and leaf nodes.
  70806. var Node = /** @class */ (function () {
  70807. function Node(polygons) {
  70808. this.plane = null;
  70809. this.front = null;
  70810. this.back = null;
  70811. this.polygons = new Array();
  70812. if (polygons) {
  70813. this.build(polygons);
  70814. }
  70815. }
  70816. Node.prototype.clone = function () {
  70817. var node = new Node();
  70818. node.plane = this.plane && this.plane.clone();
  70819. node.front = this.front && this.front.clone();
  70820. node.back = this.back && this.back.clone();
  70821. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  70822. return node;
  70823. };
  70824. // Convert solid space to empty space and empty space to solid space.
  70825. Node.prototype.invert = function () {
  70826. for (var i = 0; i < this.polygons.length; i++) {
  70827. this.polygons[i].flip();
  70828. }
  70829. if (this.plane) {
  70830. this.plane.flip();
  70831. }
  70832. if (this.front) {
  70833. this.front.invert();
  70834. }
  70835. if (this.back) {
  70836. this.back.invert();
  70837. }
  70838. var temp = this.front;
  70839. this.front = this.back;
  70840. this.back = temp;
  70841. };
  70842. // Recursively remove all polygons in `polygons` that are inside this BSP
  70843. // tree.
  70844. Node.prototype.clipPolygons = function (polygons) {
  70845. if (!this.plane)
  70846. return polygons.slice();
  70847. var front = new Array(), back = new Array();
  70848. for (var i = 0; i < polygons.length; i++) {
  70849. this.plane.splitPolygon(polygons[i], front, back, front, back);
  70850. }
  70851. if (this.front) {
  70852. front = this.front.clipPolygons(front);
  70853. }
  70854. if (this.back) {
  70855. back = this.back.clipPolygons(back);
  70856. }
  70857. else {
  70858. back = [];
  70859. }
  70860. return front.concat(back);
  70861. };
  70862. // Remove all polygons in this BSP tree that are inside the other BSP tree
  70863. // `bsp`.
  70864. Node.prototype.clipTo = function (bsp) {
  70865. this.polygons = bsp.clipPolygons(this.polygons);
  70866. if (this.front)
  70867. this.front.clipTo(bsp);
  70868. if (this.back)
  70869. this.back.clipTo(bsp);
  70870. };
  70871. // Return a list of all polygons in this BSP tree.
  70872. Node.prototype.allPolygons = function () {
  70873. var polygons = this.polygons.slice();
  70874. if (this.front)
  70875. polygons = polygons.concat(this.front.allPolygons());
  70876. if (this.back)
  70877. polygons = polygons.concat(this.back.allPolygons());
  70878. return polygons;
  70879. };
  70880. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  70881. // new polygons are filtered down to the bottom of the tree and become new
  70882. // nodes there. Each set of polygons is partitioned using the first polygon
  70883. // (no heuristic is used to pick a good split).
  70884. Node.prototype.build = function (polygons) {
  70885. if (!polygons.length)
  70886. return;
  70887. if (!this.plane)
  70888. this.plane = polygons[0].plane.clone();
  70889. var front = new Array(), back = new Array();
  70890. for (var i = 0; i < polygons.length; i++) {
  70891. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  70892. }
  70893. if (front.length) {
  70894. if (!this.front)
  70895. this.front = new Node();
  70896. this.front.build(front);
  70897. }
  70898. if (back.length) {
  70899. if (!this.back)
  70900. this.back = new Node();
  70901. this.back.build(back);
  70902. }
  70903. };
  70904. return Node;
  70905. }());
  70906. var CSG = /** @class */ (function () {
  70907. function CSG() {
  70908. this.polygons = new Array();
  70909. }
  70910. // Convert BABYLON.Mesh to BABYLON.CSG
  70911. CSG.FromMesh = function (mesh) {
  70912. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  70913. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  70914. if (mesh instanceof BABYLON.Mesh) {
  70915. mesh.computeWorldMatrix(true);
  70916. matrix = mesh.getWorldMatrix();
  70917. meshPosition = mesh.position.clone();
  70918. meshRotation = mesh.rotation.clone();
  70919. if (mesh.rotationQuaternion) {
  70920. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  70921. }
  70922. meshScaling = mesh.scaling.clone();
  70923. }
  70924. else {
  70925. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  70926. }
  70927. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70928. var subMeshes = mesh.subMeshes;
  70929. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  70930. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  70931. vertices = [];
  70932. for (var j = 0; j < 3; j++) {
  70933. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  70934. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  70935. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  70936. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  70937. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  70938. vertex = new Vertex(position, normal, uv);
  70939. vertices.push(vertex);
  70940. }
  70941. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  70942. // To handle the case of degenerated triangle
  70943. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  70944. if (polygon.plane)
  70945. polygons.push(polygon);
  70946. }
  70947. }
  70948. var csg = CSG.FromPolygons(polygons);
  70949. csg.matrix = matrix;
  70950. csg.position = meshPosition;
  70951. csg.rotation = meshRotation;
  70952. csg.scaling = meshScaling;
  70953. csg.rotationQuaternion = meshRotationQuaternion;
  70954. currentCSGMeshId++;
  70955. return csg;
  70956. };
  70957. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  70958. CSG.FromPolygons = function (polygons) {
  70959. var csg = new CSG();
  70960. csg.polygons = polygons;
  70961. return csg;
  70962. };
  70963. CSG.prototype.clone = function () {
  70964. var csg = new CSG();
  70965. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  70966. csg.copyTransformAttributes(this);
  70967. return csg;
  70968. };
  70969. CSG.prototype.union = function (csg) {
  70970. var a = new Node(this.clone().polygons);
  70971. var b = new Node(csg.clone().polygons);
  70972. a.clipTo(b);
  70973. b.clipTo(a);
  70974. b.invert();
  70975. b.clipTo(a);
  70976. b.invert();
  70977. a.build(b.allPolygons());
  70978. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70979. };
  70980. CSG.prototype.unionInPlace = function (csg) {
  70981. var a = new Node(this.polygons);
  70982. var b = new Node(csg.polygons);
  70983. a.clipTo(b);
  70984. b.clipTo(a);
  70985. b.invert();
  70986. b.clipTo(a);
  70987. b.invert();
  70988. a.build(b.allPolygons());
  70989. this.polygons = a.allPolygons();
  70990. };
  70991. CSG.prototype.subtract = function (csg) {
  70992. var a = new Node(this.clone().polygons);
  70993. var b = new Node(csg.clone().polygons);
  70994. a.invert();
  70995. a.clipTo(b);
  70996. b.clipTo(a);
  70997. b.invert();
  70998. b.clipTo(a);
  70999. b.invert();
  71000. a.build(b.allPolygons());
  71001. a.invert();
  71002. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  71003. };
  71004. CSG.prototype.subtractInPlace = function (csg) {
  71005. var a = new Node(this.polygons);
  71006. var b = new Node(csg.polygons);
  71007. a.invert();
  71008. a.clipTo(b);
  71009. b.clipTo(a);
  71010. b.invert();
  71011. b.clipTo(a);
  71012. b.invert();
  71013. a.build(b.allPolygons());
  71014. a.invert();
  71015. this.polygons = a.allPolygons();
  71016. };
  71017. CSG.prototype.intersect = function (csg) {
  71018. var a = new Node(this.clone().polygons);
  71019. var b = new Node(csg.clone().polygons);
  71020. a.invert();
  71021. b.clipTo(a);
  71022. b.invert();
  71023. a.clipTo(b);
  71024. b.clipTo(a);
  71025. a.build(b.allPolygons());
  71026. a.invert();
  71027. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  71028. };
  71029. CSG.prototype.intersectInPlace = function (csg) {
  71030. var a = new Node(this.polygons);
  71031. var b = new Node(csg.polygons);
  71032. a.invert();
  71033. b.clipTo(a);
  71034. b.invert();
  71035. a.clipTo(b);
  71036. b.clipTo(a);
  71037. a.build(b.allPolygons());
  71038. a.invert();
  71039. this.polygons = a.allPolygons();
  71040. };
  71041. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  71042. // not modified.
  71043. CSG.prototype.inverse = function () {
  71044. var csg = this.clone();
  71045. csg.inverseInPlace();
  71046. return csg;
  71047. };
  71048. CSG.prototype.inverseInPlace = function () {
  71049. this.polygons.map(function (p) { p.flip(); });
  71050. };
  71051. // This is used to keep meshes transformations so they can be restored
  71052. // when we build back a Babylon Mesh
  71053. // NB : All CSG operations are performed in world coordinates
  71054. CSG.prototype.copyTransformAttributes = function (csg) {
  71055. this.matrix = csg.matrix;
  71056. this.position = csg.position;
  71057. this.rotation = csg.rotation;
  71058. this.scaling = csg.scaling;
  71059. this.rotationQuaternion = csg.rotationQuaternion;
  71060. return this;
  71061. };
  71062. // Build Raw mesh from CSG
  71063. // Coordinates here are in world space
  71064. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  71065. var matrix = this.matrix.clone();
  71066. matrix.invert();
  71067. 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;
  71068. if (keepSubMeshes) {
  71069. // Sort Polygons, since subMeshes are indices range
  71070. polygons.sort(function (a, b) {
  71071. if (a.shared.meshId === b.shared.meshId) {
  71072. return a.shared.subMeshId - b.shared.subMeshId;
  71073. }
  71074. else {
  71075. return a.shared.meshId - b.shared.meshId;
  71076. }
  71077. });
  71078. }
  71079. for (var i = 0, il = polygons.length; i < il; i++) {
  71080. polygon = polygons[i];
  71081. // Building SubMeshes
  71082. if (!subMesh_dict[polygon.shared.meshId]) {
  71083. subMesh_dict[polygon.shared.meshId] = {};
  71084. }
  71085. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  71086. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  71087. indexStart: +Infinity,
  71088. indexEnd: -Infinity,
  71089. materialIndex: polygon.shared.materialIndex
  71090. };
  71091. }
  71092. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  71093. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  71094. polygonIndices[0] = 0;
  71095. polygonIndices[1] = j - 1;
  71096. polygonIndices[2] = j;
  71097. for (var k = 0; k < 3; k++) {
  71098. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  71099. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  71100. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  71101. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  71102. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  71103. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  71104. // Check if 2 points can be merged
  71105. if (!(typeof vertex_idx !== 'undefined' &&
  71106. normals[vertex_idx * 3] === localNormal.x &&
  71107. normals[vertex_idx * 3 + 1] === localNormal.y &&
  71108. normals[vertex_idx * 3 + 2] === localNormal.z &&
  71109. uvs[vertex_idx * 2] === uv.x &&
  71110. uvs[vertex_idx * 2 + 1] === uv.y)) {
  71111. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  71112. uvs.push(uv.x, uv.y);
  71113. normals.push(normal.x, normal.y, normal.z);
  71114. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  71115. }
  71116. indices.push(vertex_idx);
  71117. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  71118. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  71119. currentIndex++;
  71120. }
  71121. }
  71122. }
  71123. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  71124. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  71125. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  71126. mesh.setIndices(indices, null);
  71127. if (keepSubMeshes) {
  71128. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  71129. var materialIndexOffset = 0, materialMaxIndex;
  71130. mesh.subMeshes = new Array();
  71131. for (var m in subMesh_dict) {
  71132. materialMaxIndex = -1;
  71133. for (var sm in subMesh_dict[m]) {
  71134. subMesh_obj = subMesh_dict[m][sm];
  71135. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  71136. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  71137. }
  71138. materialIndexOffset += ++materialMaxIndex;
  71139. }
  71140. }
  71141. return mesh;
  71142. };
  71143. // Build Mesh from CSG taking material and transforms into account
  71144. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  71145. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  71146. mesh.material = material;
  71147. mesh.position.copyFrom(this.position);
  71148. mesh.rotation.copyFrom(this.rotation);
  71149. if (this.rotationQuaternion) {
  71150. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  71151. }
  71152. mesh.scaling.copyFrom(this.scaling);
  71153. mesh.computeWorldMatrix(true);
  71154. return mesh;
  71155. };
  71156. return CSG;
  71157. }());
  71158. BABYLON.CSG = CSG;
  71159. })(BABYLON || (BABYLON = {}));
  71160. //# sourceMappingURL=babylon.csg.js.map
  71161. var BABYLON;
  71162. (function (BABYLON) {
  71163. var LensFlare = /** @class */ (function () {
  71164. function LensFlare(size, position, color, imgUrl, system) {
  71165. this.size = size;
  71166. this.position = position;
  71167. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  71168. this.color = color || new BABYLON.Color3(1, 1, 1);
  71169. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  71170. this._system = system;
  71171. system.lensFlares.push(this);
  71172. }
  71173. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  71174. return new LensFlare(size, position, color, imgUrl, system);
  71175. };
  71176. LensFlare.prototype.dispose = function () {
  71177. if (this.texture) {
  71178. this.texture.dispose();
  71179. }
  71180. // Remove from scene
  71181. var index = this._system.lensFlares.indexOf(this);
  71182. this._system.lensFlares.splice(index, 1);
  71183. };
  71184. ;
  71185. return LensFlare;
  71186. }());
  71187. BABYLON.LensFlare = LensFlare;
  71188. })(BABYLON || (BABYLON = {}));
  71189. //# sourceMappingURL=babylon.lensFlare.js.map
  71190. var BABYLON;
  71191. (function (BABYLON) {
  71192. var LensFlareSystem = /** @class */ (function () {
  71193. function LensFlareSystem(name, emitter, scene) {
  71194. this.name = name;
  71195. this.lensFlares = new Array();
  71196. this.borderLimit = 300;
  71197. this.viewportBorder = 0;
  71198. this.layerMask = 0x0FFFFFFF;
  71199. this._vertexBuffers = {};
  71200. this._isEnabled = true;
  71201. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71202. this._emitter = emitter;
  71203. this.id = name;
  71204. scene.lensFlareSystems.push(this);
  71205. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  71206. var engine = scene.getEngine();
  71207. // VBO
  71208. var vertices = [];
  71209. vertices.push(1, 1);
  71210. vertices.push(-1, 1);
  71211. vertices.push(-1, -1);
  71212. vertices.push(1, -1);
  71213. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71214. // Indices
  71215. var indices = [];
  71216. indices.push(0);
  71217. indices.push(1);
  71218. indices.push(2);
  71219. indices.push(0);
  71220. indices.push(2);
  71221. indices.push(3);
  71222. this._indexBuffer = engine.createIndexBuffer(indices);
  71223. // Effects
  71224. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  71225. }
  71226. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  71227. get: function () {
  71228. return this._isEnabled;
  71229. },
  71230. set: function (value) {
  71231. this._isEnabled = value;
  71232. },
  71233. enumerable: true,
  71234. configurable: true
  71235. });
  71236. LensFlareSystem.prototype.getScene = function () {
  71237. return this._scene;
  71238. };
  71239. LensFlareSystem.prototype.getEmitter = function () {
  71240. return this._emitter;
  71241. };
  71242. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  71243. this._emitter = newEmitter;
  71244. };
  71245. LensFlareSystem.prototype.getEmitterPosition = function () {
  71246. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  71247. };
  71248. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  71249. var position = this.getEmitterPosition();
  71250. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  71251. this._positionX = position.x;
  71252. this._positionY = position.y;
  71253. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  71254. if (this.viewportBorder > 0) {
  71255. globalViewport.x -= this.viewportBorder;
  71256. globalViewport.y -= this.viewportBorder;
  71257. globalViewport.width += this.viewportBorder * 2;
  71258. globalViewport.height += this.viewportBorder * 2;
  71259. position.x += this.viewportBorder;
  71260. position.y += this.viewportBorder;
  71261. this._positionX += this.viewportBorder;
  71262. this._positionY += this.viewportBorder;
  71263. }
  71264. if (position.z > 0) {
  71265. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  71266. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  71267. return true;
  71268. }
  71269. return true;
  71270. }
  71271. return false;
  71272. };
  71273. LensFlareSystem.prototype._isVisible = function () {
  71274. if (!this._isEnabled || !this._scene.activeCamera) {
  71275. return false;
  71276. }
  71277. var emitterPosition = this.getEmitterPosition();
  71278. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  71279. var distance = direction.length();
  71280. direction.normalize();
  71281. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  71282. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  71283. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  71284. };
  71285. LensFlareSystem.prototype.render = function () {
  71286. if (!this._effect.isReady() || !this._scene.activeCamera)
  71287. return false;
  71288. var engine = this._scene.getEngine();
  71289. var viewport = this._scene.activeCamera.viewport;
  71290. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  71291. // Position
  71292. if (!this.computeEffectivePosition(globalViewport)) {
  71293. return false;
  71294. }
  71295. // Visibility
  71296. if (!this._isVisible()) {
  71297. return false;
  71298. }
  71299. // Intensity
  71300. var awayX;
  71301. var awayY;
  71302. if (this._positionX < this.borderLimit + globalViewport.x) {
  71303. awayX = this.borderLimit + globalViewport.x - this._positionX;
  71304. }
  71305. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  71306. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  71307. }
  71308. else {
  71309. awayX = 0;
  71310. }
  71311. if (this._positionY < this.borderLimit + globalViewport.y) {
  71312. awayY = this.borderLimit + globalViewport.y - this._positionY;
  71313. }
  71314. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  71315. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  71316. }
  71317. else {
  71318. awayY = 0;
  71319. }
  71320. var away = (awayX > awayY) ? awayX : awayY;
  71321. away -= this.viewportBorder;
  71322. if (away > this.borderLimit) {
  71323. away = this.borderLimit;
  71324. }
  71325. var intensity = 1.0 - (away / this.borderLimit);
  71326. if (intensity < 0) {
  71327. return false;
  71328. }
  71329. if (intensity > 1.0) {
  71330. intensity = 1.0;
  71331. }
  71332. if (this.viewportBorder > 0) {
  71333. globalViewport.x += this.viewportBorder;
  71334. globalViewport.y += this.viewportBorder;
  71335. globalViewport.width -= this.viewportBorder * 2;
  71336. globalViewport.height -= this.viewportBorder * 2;
  71337. this._positionX -= this.viewportBorder;
  71338. this._positionY -= this.viewportBorder;
  71339. }
  71340. // Position
  71341. var centerX = globalViewport.x + globalViewport.width / 2;
  71342. var centerY = globalViewport.y + globalViewport.height / 2;
  71343. var distX = centerX - this._positionX;
  71344. var distY = centerY - this._positionY;
  71345. // Effects
  71346. engine.enableEffect(this._effect);
  71347. engine.setState(false);
  71348. engine.setDepthBuffer(false);
  71349. // VBOs
  71350. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71351. // Flares
  71352. for (var index = 0; index < this.lensFlares.length; index++) {
  71353. var flare = this.lensFlares[index];
  71354. engine.setAlphaMode(flare.alphaMode);
  71355. var x = centerX - (distX * flare.position);
  71356. var y = centerY - (distY * flare.position);
  71357. var cw = flare.size;
  71358. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  71359. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  71360. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  71361. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  71362. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  71363. // Texture
  71364. this._effect.setTexture("textureSampler", flare.texture);
  71365. // Color
  71366. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  71367. // Draw order
  71368. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71369. }
  71370. engine.setDepthBuffer(true);
  71371. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71372. return true;
  71373. };
  71374. LensFlareSystem.prototype.dispose = function () {
  71375. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71376. if (vertexBuffer) {
  71377. vertexBuffer.dispose();
  71378. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71379. }
  71380. if (this._indexBuffer) {
  71381. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71382. this._indexBuffer = null;
  71383. }
  71384. while (this.lensFlares.length) {
  71385. this.lensFlares[0].dispose();
  71386. }
  71387. // Remove from scene
  71388. var index = this._scene.lensFlareSystems.indexOf(this);
  71389. this._scene.lensFlareSystems.splice(index, 1);
  71390. };
  71391. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  71392. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  71393. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  71394. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  71395. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  71396. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  71397. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  71398. var parsedFlare = parsedLensFlareSystem.flares[index];
  71399. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  71400. }
  71401. return lensFlareSystem;
  71402. };
  71403. LensFlareSystem.prototype.serialize = function () {
  71404. var serializationObject = {};
  71405. serializationObject.id = this.id;
  71406. serializationObject.name = this.name;
  71407. serializationObject.emitterId = this.getEmitter().id;
  71408. serializationObject.borderLimit = this.borderLimit;
  71409. serializationObject.flares = [];
  71410. for (var index = 0; index < this.lensFlares.length; index++) {
  71411. var flare = this.lensFlares[index];
  71412. serializationObject.flares.push({
  71413. size: flare.size,
  71414. position: flare.position,
  71415. color: flare.color.asArray(),
  71416. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  71417. });
  71418. }
  71419. return serializationObject;
  71420. };
  71421. return LensFlareSystem;
  71422. }());
  71423. BABYLON.LensFlareSystem = LensFlareSystem;
  71424. })(BABYLON || (BABYLON = {}));
  71425. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  71426. var BABYLON;
  71427. (function (BABYLON) {
  71428. /**
  71429. * This is a holder class for the physics joint created by the physics plugin.
  71430. * It holds a set of functions to control the underlying joint.
  71431. */
  71432. var PhysicsJoint = /** @class */ (function () {
  71433. function PhysicsJoint(type, jointData) {
  71434. this.type = type;
  71435. this.jointData = jointData;
  71436. jointData.nativeParams = jointData.nativeParams || {};
  71437. }
  71438. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  71439. get: function () {
  71440. return this._physicsJoint;
  71441. },
  71442. set: function (newJoint) {
  71443. if (this._physicsJoint) {
  71444. //remove from the wolrd
  71445. }
  71446. this._physicsJoint = newJoint;
  71447. },
  71448. enumerable: true,
  71449. configurable: true
  71450. });
  71451. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  71452. set: function (physicsPlugin) {
  71453. this._physicsPlugin = physicsPlugin;
  71454. },
  71455. enumerable: true,
  71456. configurable: true
  71457. });
  71458. /**
  71459. * Execute a function that is physics-plugin specific.
  71460. * @param {Function} func the function that will be executed.
  71461. * It accepts two parameters: the physics world and the physics joint.
  71462. */
  71463. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  71464. func(this._physicsPlugin.world, this._physicsJoint);
  71465. };
  71466. //TODO check if the native joints are the same
  71467. //Joint Types
  71468. PhysicsJoint.DistanceJoint = 0;
  71469. PhysicsJoint.HingeJoint = 1;
  71470. PhysicsJoint.BallAndSocketJoint = 2;
  71471. PhysicsJoint.WheelJoint = 3;
  71472. PhysicsJoint.SliderJoint = 4;
  71473. //OIMO
  71474. PhysicsJoint.PrismaticJoint = 5;
  71475. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  71476. PhysicsJoint.UniversalJoint = 6;
  71477. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  71478. //Cannon
  71479. //Similar to a Ball-Joint. Different in params
  71480. PhysicsJoint.PointToPointJoint = 8;
  71481. //Cannon only at the moment
  71482. PhysicsJoint.SpringJoint = 9;
  71483. PhysicsJoint.LockJoint = 10;
  71484. return PhysicsJoint;
  71485. }());
  71486. BABYLON.PhysicsJoint = PhysicsJoint;
  71487. /**
  71488. * A class representing a physics distance joint.
  71489. */
  71490. var DistanceJoint = /** @class */ (function (_super) {
  71491. __extends(DistanceJoint, _super);
  71492. function DistanceJoint(jointData) {
  71493. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  71494. }
  71495. /**
  71496. * Update the predefined distance.
  71497. */
  71498. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  71499. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  71500. };
  71501. return DistanceJoint;
  71502. }(PhysicsJoint));
  71503. BABYLON.DistanceJoint = DistanceJoint;
  71504. var MotorEnabledJoint = /** @class */ (function (_super) {
  71505. __extends(MotorEnabledJoint, _super);
  71506. function MotorEnabledJoint(type, jointData) {
  71507. return _super.call(this, type, jointData) || this;
  71508. }
  71509. /**
  71510. * Set the motor values.
  71511. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71512. * @param {number} force the force to apply
  71513. * @param {number} maxForce max force for this motor.
  71514. */
  71515. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  71516. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  71517. };
  71518. /**
  71519. * Set the motor's limits.
  71520. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71521. */
  71522. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  71523. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  71524. };
  71525. return MotorEnabledJoint;
  71526. }(PhysicsJoint));
  71527. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  71528. /**
  71529. * This class represents a single hinge physics joint
  71530. */
  71531. var HingeJoint = /** @class */ (function (_super) {
  71532. __extends(HingeJoint, _super);
  71533. function HingeJoint(jointData) {
  71534. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  71535. }
  71536. /**
  71537. * Set the motor values.
  71538. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71539. * @param {number} force the force to apply
  71540. * @param {number} maxForce max force for this motor.
  71541. */
  71542. HingeJoint.prototype.setMotor = function (force, maxForce) {
  71543. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  71544. };
  71545. /**
  71546. * Set the motor's limits.
  71547. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71548. */
  71549. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  71550. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  71551. };
  71552. return HingeJoint;
  71553. }(MotorEnabledJoint));
  71554. BABYLON.HingeJoint = HingeJoint;
  71555. /**
  71556. * This class represents a dual hinge physics joint (same as wheel joint)
  71557. */
  71558. var Hinge2Joint = /** @class */ (function (_super) {
  71559. __extends(Hinge2Joint, _super);
  71560. function Hinge2Joint(jointData) {
  71561. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  71562. }
  71563. /**
  71564. * Set the motor values.
  71565. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71566. * @param {number} force the force to apply
  71567. * @param {number} maxForce max force for this motor.
  71568. * @param {motorIndex} the motor's index, 0 or 1.
  71569. */
  71570. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  71571. if (motorIndex === void 0) { motorIndex = 0; }
  71572. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  71573. };
  71574. /**
  71575. * Set the motor limits.
  71576. * Attention, this function is plugin specific. Engines won't react 100% the same.
  71577. * @param {number} upperLimit the upper limit
  71578. * @param {number} lowerLimit lower limit
  71579. * @param {motorIndex} the motor's index, 0 or 1.
  71580. */
  71581. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  71582. if (motorIndex === void 0) { motorIndex = 0; }
  71583. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  71584. };
  71585. return Hinge2Joint;
  71586. }(MotorEnabledJoint));
  71587. BABYLON.Hinge2Joint = Hinge2Joint;
  71588. })(BABYLON || (BABYLON = {}));
  71589. //# sourceMappingURL=babylon.physicsJoint.js.map
  71590. var BABYLON;
  71591. (function (BABYLON) {
  71592. var PhysicsImpostor = /** @class */ (function () {
  71593. function PhysicsImpostor(object, type, _options, _scene) {
  71594. if (_options === void 0) { _options = { mass: 0 }; }
  71595. var _this = this;
  71596. this.object = object;
  71597. this.type = type;
  71598. this._options = _options;
  71599. this._scene = _scene;
  71600. this._bodyUpdateRequired = false;
  71601. this._onBeforePhysicsStepCallbacks = new Array();
  71602. this._onAfterPhysicsStepCallbacks = new Array();
  71603. this._onPhysicsCollideCallbacks = [];
  71604. this._deltaPosition = BABYLON.Vector3.Zero();
  71605. this._isDisposed = false;
  71606. //temp variables for parent rotation calculations
  71607. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  71608. this._tmpQuat = new BABYLON.Quaternion();
  71609. this._tmpQuat2 = new BABYLON.Quaternion();
  71610. /**
  71611. * this function is executed by the physics engine.
  71612. */
  71613. this.beforeStep = function () {
  71614. if (!_this._physicsEngine) {
  71615. return;
  71616. }
  71617. _this.object.translate(_this._deltaPosition, -1);
  71618. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  71619. _this.object.computeWorldMatrix(false);
  71620. if (_this.object.parent && _this.object.rotationQuaternion) {
  71621. _this.getParentsRotation();
  71622. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  71623. }
  71624. else {
  71625. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  71626. }
  71627. if (!_this._options.disableBidirectionalTransformation) {
  71628. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  71629. }
  71630. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  71631. func(_this);
  71632. });
  71633. };
  71634. /**
  71635. * this function is executed by the physics engine.
  71636. */
  71637. this.afterStep = function () {
  71638. if (!_this._physicsEngine) {
  71639. return;
  71640. }
  71641. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  71642. func(_this);
  71643. });
  71644. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  71645. // object has now its world rotation. needs to be converted to local.
  71646. if (_this.object.parent && _this.object.rotationQuaternion) {
  71647. _this.getParentsRotation();
  71648. _this._tmpQuat.conjugateInPlace();
  71649. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  71650. }
  71651. // take the position set and make it the absolute position of this object.
  71652. _this.object.setAbsolutePosition(_this.object.position);
  71653. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  71654. _this.object.translate(_this._deltaPosition, 1);
  71655. };
  71656. /**
  71657. * Legacy collision detection event support
  71658. */
  71659. this.onCollideEvent = null;
  71660. //event and body object due to cannon's event-based architecture.
  71661. this.onCollide = function (e) {
  71662. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  71663. return;
  71664. }
  71665. if (!_this._physicsEngine) {
  71666. return;
  71667. }
  71668. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  71669. if (otherImpostor) {
  71670. // Legacy collision detection event support
  71671. if (_this.onCollideEvent) {
  71672. _this.onCollideEvent(_this, otherImpostor);
  71673. }
  71674. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  71675. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  71676. }).forEach(function (obj) {
  71677. obj.callback(_this, otherImpostor);
  71678. });
  71679. }
  71680. };
  71681. //sanity check!
  71682. if (!this.object) {
  71683. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  71684. return;
  71685. }
  71686. //legacy support for old syntax.
  71687. if (!this._scene && object.getScene) {
  71688. this._scene = object.getScene();
  71689. }
  71690. if (!this._scene) {
  71691. return;
  71692. }
  71693. this._physicsEngine = this._scene.getPhysicsEngine();
  71694. if (!this._physicsEngine) {
  71695. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  71696. }
  71697. else {
  71698. //set the object's quaternion, if not set
  71699. if (!this.object.rotationQuaternion) {
  71700. if (this.object.rotation) {
  71701. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  71702. }
  71703. else {
  71704. this.object.rotationQuaternion = new BABYLON.Quaternion();
  71705. }
  71706. }
  71707. //default options params
  71708. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  71709. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  71710. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  71711. this._joints = [];
  71712. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  71713. if (!this.object.parent || this._options.ignoreParent) {
  71714. this._init();
  71715. }
  71716. else if (this.object.parent.physicsImpostor) {
  71717. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  71718. }
  71719. }
  71720. }
  71721. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  71722. get: function () {
  71723. return this._isDisposed;
  71724. },
  71725. enumerable: true,
  71726. configurable: true
  71727. });
  71728. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  71729. get: function () {
  71730. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  71731. },
  71732. set: function (value) {
  71733. this.setMass(value);
  71734. },
  71735. enumerable: true,
  71736. configurable: true
  71737. });
  71738. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  71739. get: function () {
  71740. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  71741. },
  71742. set: function (value) {
  71743. if (!this._physicsEngine) {
  71744. return;
  71745. }
  71746. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  71747. },
  71748. enumerable: true,
  71749. configurable: true
  71750. });
  71751. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  71752. get: function () {
  71753. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  71754. },
  71755. set: function (value) {
  71756. if (!this._physicsEngine) {
  71757. return;
  71758. }
  71759. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  71760. },
  71761. enumerable: true,
  71762. configurable: true
  71763. });
  71764. /**
  71765. * This function will completly initialize this impostor.
  71766. * It will create a new body - but only if this mesh has no parent.
  71767. * If it has, this impostor will not be used other than to define the impostor
  71768. * of the child mesh.
  71769. */
  71770. PhysicsImpostor.prototype._init = function () {
  71771. if (!this._physicsEngine) {
  71772. return;
  71773. }
  71774. this._physicsEngine.removeImpostor(this);
  71775. this.physicsBody = null;
  71776. this._parent = this._parent || this._getPhysicsParent();
  71777. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  71778. this._physicsEngine.addImpostor(this);
  71779. }
  71780. };
  71781. PhysicsImpostor.prototype._getPhysicsParent = function () {
  71782. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  71783. var parentMesh = this.object.parent;
  71784. return parentMesh.physicsImpostor;
  71785. }
  71786. return null;
  71787. };
  71788. /**
  71789. * Should a new body be generated.
  71790. */
  71791. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  71792. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  71793. };
  71794. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  71795. this.forceUpdate();
  71796. };
  71797. /**
  71798. * Force a regeneration of this or the parent's impostor's body.
  71799. * Use under cautious - This will remove all joints already implemented.
  71800. */
  71801. PhysicsImpostor.prototype.forceUpdate = function () {
  71802. this._init();
  71803. if (this.parent && !this._options.ignoreParent) {
  71804. this.parent.forceUpdate();
  71805. }
  71806. };
  71807. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  71808. /*public get mesh(): AbstractMesh {
  71809. return this._mesh;
  71810. }*/
  71811. /**
  71812. * Gets the body that holds this impostor. Either its own, or its parent.
  71813. */
  71814. get: function () {
  71815. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  71816. },
  71817. /**
  71818. * Set the physics body. Used mainly by the physics engine/plugin
  71819. */
  71820. set: function (physicsBody) {
  71821. if (this._physicsBody && this._physicsEngine) {
  71822. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  71823. }
  71824. this._physicsBody = physicsBody;
  71825. this.resetUpdateFlags();
  71826. },
  71827. enumerable: true,
  71828. configurable: true
  71829. });
  71830. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  71831. get: function () {
  71832. return !this._options.ignoreParent && this._parent ? this._parent : null;
  71833. },
  71834. set: function (value) {
  71835. this._parent = value;
  71836. },
  71837. enumerable: true,
  71838. configurable: true
  71839. });
  71840. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  71841. this._bodyUpdateRequired = false;
  71842. };
  71843. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  71844. if (this.object.getBoundingInfo) {
  71845. var q = this.object.rotationQuaternion;
  71846. //reset rotation
  71847. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  71848. //calculate the world matrix with no rotation
  71849. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71850. var boundingInfo = this.object.getBoundingInfo();
  71851. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  71852. //bring back the rotation
  71853. this.object.rotationQuaternion = q;
  71854. //calculate the world matrix with the new rotation
  71855. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71856. return size;
  71857. }
  71858. else {
  71859. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  71860. }
  71861. };
  71862. PhysicsImpostor.prototype.getObjectCenter = function () {
  71863. if (this.object.getBoundingInfo) {
  71864. var boundingInfo = this.object.getBoundingInfo();
  71865. return boundingInfo.boundingBox.centerWorld;
  71866. }
  71867. else {
  71868. return this.object.position;
  71869. }
  71870. };
  71871. /**
  71872. * Get a specific parametes from the options parameter.
  71873. */
  71874. PhysicsImpostor.prototype.getParam = function (paramName) {
  71875. return this._options[paramName];
  71876. };
  71877. /**
  71878. * Sets a specific parameter in the options given to the physics plugin
  71879. */
  71880. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  71881. this._options[paramName] = value;
  71882. this._bodyUpdateRequired = true;
  71883. };
  71884. /**
  71885. * Specifically change the body's mass option. Won't recreate the physics body object
  71886. */
  71887. PhysicsImpostor.prototype.setMass = function (mass) {
  71888. if (this.getParam("mass") !== mass) {
  71889. this.setParam("mass", mass);
  71890. }
  71891. if (this._physicsEngine) {
  71892. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  71893. }
  71894. };
  71895. PhysicsImpostor.prototype.getLinearVelocity = function () {
  71896. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  71897. };
  71898. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  71899. if (this._physicsEngine) {
  71900. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  71901. }
  71902. };
  71903. PhysicsImpostor.prototype.getAngularVelocity = function () {
  71904. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  71905. };
  71906. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  71907. if (this._physicsEngine) {
  71908. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  71909. }
  71910. };
  71911. /**
  71912. * Execute a function with the physics plugin native code.
  71913. * Provide a function the will have two variables - the world object and the physics body object.
  71914. */
  71915. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  71916. if (this._physicsEngine) {
  71917. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  71918. }
  71919. };
  71920. /**
  71921. * Register a function that will be executed before the physics world is stepping forward.
  71922. */
  71923. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  71924. this._onBeforePhysicsStepCallbacks.push(func);
  71925. };
  71926. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  71927. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  71928. if (index > -1) {
  71929. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  71930. }
  71931. else {
  71932. BABYLON.Tools.Warn("Function to remove was not found");
  71933. }
  71934. };
  71935. /**
  71936. * Register a function that will be executed after the physics step
  71937. */
  71938. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  71939. this._onAfterPhysicsStepCallbacks.push(func);
  71940. };
  71941. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  71942. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  71943. if (index > -1) {
  71944. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  71945. }
  71946. else {
  71947. BABYLON.Tools.Warn("Function to remove was not found");
  71948. }
  71949. };
  71950. /**
  71951. * register a function that will be executed when this impostor collides against a different body.
  71952. */
  71953. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  71954. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71955. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  71956. };
  71957. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  71958. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71959. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  71960. if (index > -1) {
  71961. this._onPhysicsCollideCallbacks.splice(index, 1);
  71962. }
  71963. else {
  71964. BABYLON.Tools.Warn("Function to remove was not found");
  71965. }
  71966. };
  71967. PhysicsImpostor.prototype.getParentsRotation = function () {
  71968. var parent = this.object.parent;
  71969. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  71970. while (parent) {
  71971. if (parent.rotationQuaternion) {
  71972. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  71973. }
  71974. else {
  71975. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  71976. }
  71977. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  71978. parent = parent.parent;
  71979. }
  71980. return this._tmpQuat;
  71981. };
  71982. /**
  71983. * Apply a force
  71984. */
  71985. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  71986. if (this._physicsEngine) {
  71987. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  71988. }
  71989. return this;
  71990. };
  71991. /**
  71992. * Apply an impulse
  71993. */
  71994. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  71995. if (this._physicsEngine) {
  71996. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  71997. }
  71998. return this;
  71999. };
  72000. /**
  72001. * A help function to create a joint.
  72002. */
  72003. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  72004. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  72005. this.addJoint(otherImpostor, joint);
  72006. return this;
  72007. };
  72008. /**
  72009. * Add a joint to this impostor with a different impostor.
  72010. */
  72011. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  72012. this._joints.push({
  72013. otherImpostor: otherImpostor,
  72014. joint: joint
  72015. });
  72016. if (this._physicsEngine) {
  72017. this._physicsEngine.addJoint(this, otherImpostor, joint);
  72018. }
  72019. return this;
  72020. };
  72021. /**
  72022. * Will keep this body still, in a sleep mode.
  72023. */
  72024. PhysicsImpostor.prototype.sleep = function () {
  72025. if (this._physicsEngine) {
  72026. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  72027. }
  72028. return this;
  72029. };
  72030. /**
  72031. * Wake the body up.
  72032. */
  72033. PhysicsImpostor.prototype.wakeUp = function () {
  72034. if (this._physicsEngine) {
  72035. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  72036. }
  72037. return this;
  72038. };
  72039. PhysicsImpostor.prototype.clone = function (newObject) {
  72040. if (!newObject)
  72041. return null;
  72042. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  72043. };
  72044. PhysicsImpostor.prototype.dispose = function () {
  72045. var _this = this;
  72046. //no dispose if no physics engine is available.
  72047. if (!this._physicsEngine) {
  72048. return;
  72049. }
  72050. this._joints.forEach(function (j) {
  72051. if (_this._physicsEngine) {
  72052. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  72053. }
  72054. });
  72055. //dispose the physics body
  72056. this._physicsEngine.removeImpostor(this);
  72057. if (this.parent) {
  72058. this.parent.forceUpdate();
  72059. }
  72060. else {
  72061. /*this._object.getChildMeshes().forEach(function(mesh) {
  72062. if (mesh.physicsImpostor) {
  72063. if (disposeChildren) {
  72064. mesh.physicsImpostor.dispose();
  72065. mesh.physicsImpostor = null;
  72066. }
  72067. }
  72068. })*/
  72069. }
  72070. this._isDisposed = true;
  72071. };
  72072. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  72073. this._deltaPosition.copyFrom(position);
  72074. };
  72075. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  72076. if (!this._deltaRotation) {
  72077. this._deltaRotation = new BABYLON.Quaternion();
  72078. }
  72079. this._deltaRotation.copyFrom(rotation);
  72080. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  72081. };
  72082. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  72083. if (this._physicsEngine) {
  72084. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  72085. }
  72086. return this;
  72087. };
  72088. PhysicsImpostor.prototype.getRadius = function () {
  72089. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  72090. };
  72091. /**
  72092. * Sync a bone with this impostor
  72093. * @param bone The bone to sync to the impostor.
  72094. * @param boneMesh The mesh that the bone is influencing.
  72095. * @param jointPivot The pivot of the joint / bone in local space.
  72096. * @param distToJoint Optional distance from the impostor to the joint.
  72097. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  72098. */
  72099. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  72100. var tempVec = PhysicsImpostor._tmpVecs[0];
  72101. var mesh = this.object;
  72102. if (mesh.rotationQuaternion) {
  72103. if (adjustRotation) {
  72104. var tempQuat = PhysicsImpostor._tmpQuat;
  72105. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  72106. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  72107. }
  72108. else {
  72109. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  72110. }
  72111. }
  72112. tempVec.x = 0;
  72113. tempVec.y = 0;
  72114. tempVec.z = 0;
  72115. if (jointPivot) {
  72116. tempVec.x = jointPivot.x;
  72117. tempVec.y = jointPivot.y;
  72118. tempVec.z = jointPivot.z;
  72119. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  72120. if (distToJoint === undefined || distToJoint === null) {
  72121. distToJoint = jointPivot.length();
  72122. }
  72123. tempVec.x *= distToJoint;
  72124. tempVec.y *= distToJoint;
  72125. tempVec.z *= distToJoint;
  72126. }
  72127. if (bone.getParent()) {
  72128. tempVec.addInPlace(mesh.getAbsolutePosition());
  72129. bone.setAbsolutePosition(tempVec, boneMesh);
  72130. }
  72131. else {
  72132. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  72133. boneMesh.position.x -= tempVec.x;
  72134. boneMesh.position.y -= tempVec.y;
  72135. boneMesh.position.z -= tempVec.z;
  72136. }
  72137. };
  72138. /**
  72139. * Sync impostor to a bone
  72140. * @param bone The bone that the impostor will be synced to.
  72141. * @param boneMesh The mesh that the bone is influencing.
  72142. * @param jointPivot The pivot of the joint / bone in local space.
  72143. * @param distToJoint Optional distance from the impostor to the joint.
  72144. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  72145. * @param boneAxis Optional vector3 axis the bone is aligned with
  72146. */
  72147. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  72148. var mesh = this.object;
  72149. if (mesh.rotationQuaternion) {
  72150. if (adjustRotation) {
  72151. var tempQuat = PhysicsImpostor._tmpQuat;
  72152. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  72153. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  72154. }
  72155. else {
  72156. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  72157. }
  72158. }
  72159. var pos = PhysicsImpostor._tmpVecs[0];
  72160. var boneDir = PhysicsImpostor._tmpVecs[1];
  72161. if (!boneAxis) {
  72162. boneAxis = PhysicsImpostor._tmpVecs[2];
  72163. boneAxis.x = 0;
  72164. boneAxis.y = 1;
  72165. boneAxis.z = 0;
  72166. }
  72167. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  72168. bone.getAbsolutePositionToRef(boneMesh, pos);
  72169. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  72170. distToJoint = jointPivot.length();
  72171. }
  72172. if (distToJoint !== undefined && distToJoint !== null) {
  72173. pos.x += boneDir.x * distToJoint;
  72174. pos.y += boneDir.y * distToJoint;
  72175. pos.z += boneDir.z * distToJoint;
  72176. }
  72177. mesh.setAbsolutePosition(pos);
  72178. };
  72179. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  72180. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  72181. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72182. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  72183. //Impostor types
  72184. PhysicsImpostor.NoImpostor = 0;
  72185. PhysicsImpostor.SphereImpostor = 1;
  72186. PhysicsImpostor.BoxImpostor = 2;
  72187. PhysicsImpostor.PlaneImpostor = 3;
  72188. PhysicsImpostor.MeshImpostor = 4;
  72189. PhysicsImpostor.CylinderImpostor = 7;
  72190. PhysicsImpostor.ParticleImpostor = 8;
  72191. PhysicsImpostor.HeightmapImpostor = 9;
  72192. return PhysicsImpostor;
  72193. }());
  72194. BABYLON.PhysicsImpostor = PhysicsImpostor;
  72195. })(BABYLON || (BABYLON = {}));
  72196. //# sourceMappingURL=babylon.physicsImpostor.js.map
  72197. var BABYLON;
  72198. (function (BABYLON) {
  72199. var PhysicsEngine = /** @class */ (function () {
  72200. function PhysicsEngine(gravity, _physicsPlugin) {
  72201. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  72202. this._physicsPlugin = _physicsPlugin;
  72203. //new methods and parameters
  72204. this._impostors = [];
  72205. this._joints = [];
  72206. if (!this._physicsPlugin.isSupported()) {
  72207. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  72208. + "Please make sure it is included.");
  72209. }
  72210. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  72211. this.setGravity(gravity);
  72212. this.setTimeStep();
  72213. }
  72214. PhysicsEngine.prototype.setGravity = function (gravity) {
  72215. this.gravity = gravity;
  72216. this._physicsPlugin.setGravity(this.gravity);
  72217. };
  72218. /**
  72219. * Set the time step of the physics engine.
  72220. * default is 1/60.
  72221. * To slow it down, enter 1/600 for example.
  72222. * To speed it up, 1/30
  72223. * @param {number} newTimeStep the new timestep to apply to this world.
  72224. */
  72225. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  72226. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  72227. this._physicsPlugin.setTimeStep(newTimeStep);
  72228. };
  72229. /**
  72230. * Get the time step of the physics engine.
  72231. */
  72232. PhysicsEngine.prototype.getTimeStep = function () {
  72233. return this._physicsPlugin.getTimeStep();
  72234. };
  72235. PhysicsEngine.prototype.dispose = function () {
  72236. this._impostors.forEach(function (impostor) {
  72237. impostor.dispose();
  72238. });
  72239. this._physicsPlugin.dispose();
  72240. };
  72241. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  72242. return this._physicsPlugin.name;
  72243. };
  72244. /**
  72245. * Adding a new impostor for the impostor tracking.
  72246. * This will be done by the impostor itself.
  72247. * @param {PhysicsImpostor} impostor the impostor to add
  72248. */
  72249. PhysicsEngine.prototype.addImpostor = function (impostor) {
  72250. impostor.uniqueId = this._impostors.push(impostor);
  72251. //if no parent, generate the body
  72252. if (!impostor.parent) {
  72253. this._physicsPlugin.generatePhysicsBody(impostor);
  72254. }
  72255. };
  72256. /**
  72257. * Remove an impostor from the engine.
  72258. * This impostor and its mesh will not longer be updated by the physics engine.
  72259. * @param {PhysicsImpostor} impostor the impostor to remove
  72260. */
  72261. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  72262. var index = this._impostors.indexOf(impostor);
  72263. if (index > -1) {
  72264. var removed = this._impostors.splice(index, 1);
  72265. //Is it needed?
  72266. if (removed.length) {
  72267. //this will also remove it from the world.
  72268. removed[0].physicsBody = null;
  72269. }
  72270. }
  72271. };
  72272. /**
  72273. * Add a joint to the physics engine
  72274. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  72275. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  72276. * @param {PhysicsJoint} the joint that will connect both impostors.
  72277. */
  72278. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  72279. var impostorJoint = {
  72280. mainImpostor: mainImpostor,
  72281. connectedImpostor: connectedImpostor,
  72282. joint: joint
  72283. };
  72284. joint.physicsPlugin = this._physicsPlugin;
  72285. this._joints.push(impostorJoint);
  72286. this._physicsPlugin.generateJoint(impostorJoint);
  72287. };
  72288. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  72289. var matchingJoints = this._joints.filter(function (impostorJoint) {
  72290. return (impostorJoint.connectedImpostor === connectedImpostor
  72291. && impostorJoint.joint === joint
  72292. && impostorJoint.mainImpostor === mainImpostor);
  72293. });
  72294. if (matchingJoints.length) {
  72295. this._physicsPlugin.removeJoint(matchingJoints[0]);
  72296. //TODO remove it from the list as well
  72297. }
  72298. };
  72299. /**
  72300. * Called by the scene. no need to call it.
  72301. */
  72302. PhysicsEngine.prototype._step = function (delta) {
  72303. var _this = this;
  72304. //check if any mesh has no body / requires an update
  72305. this._impostors.forEach(function (impostor) {
  72306. if (impostor.isBodyInitRequired()) {
  72307. _this._physicsPlugin.generatePhysicsBody(impostor);
  72308. }
  72309. });
  72310. if (delta > 0.1) {
  72311. delta = 0.1;
  72312. }
  72313. else if (delta <= 0) {
  72314. delta = 1.0 / 60.0;
  72315. }
  72316. this._physicsPlugin.executeStep(delta, this._impostors);
  72317. };
  72318. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  72319. return this._physicsPlugin;
  72320. };
  72321. PhysicsEngine.prototype.getImpostors = function () {
  72322. return this._impostors;
  72323. };
  72324. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  72325. for (var i = 0; i < this._impostors.length; ++i) {
  72326. if (this._impostors[i].object === object) {
  72327. return this._impostors[i];
  72328. }
  72329. }
  72330. return null;
  72331. };
  72332. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  72333. for (var i = 0; i < this._impostors.length; ++i) {
  72334. if (this._impostors[i].physicsBody === body) {
  72335. return this._impostors[i];
  72336. }
  72337. }
  72338. return null;
  72339. };
  72340. // Statics
  72341. PhysicsEngine.Epsilon = 0.001;
  72342. return PhysicsEngine;
  72343. }());
  72344. BABYLON.PhysicsEngine = PhysicsEngine;
  72345. })(BABYLON || (BABYLON = {}));
  72346. //# sourceMappingURL=babylon.physicsEngine.js.map
  72347. var BABYLON;
  72348. (function (BABYLON) {
  72349. var PhysicsHelper = /** @class */ (function () {
  72350. function PhysicsHelper(scene) {
  72351. this._scene = scene;
  72352. this._physicsEngine = this._scene.getPhysicsEngine();
  72353. if (!this._physicsEngine) {
  72354. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  72355. }
  72356. }
  72357. /**
  72358. * @param {Vector3} origin the origin of the explosion
  72359. * @param {number} radius the explosion radius
  72360. * @param {number} strength the explosion strength
  72361. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  72362. */
  72363. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  72364. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  72365. if (!this._physicsEngine) {
  72366. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  72367. return null;
  72368. }
  72369. var impostors = this._physicsEngine.getImpostors();
  72370. if (impostors.length === 0) {
  72371. return null;
  72372. }
  72373. var event = new PhysicsRadialExplosionEvent(this._scene);
  72374. impostors.forEach(function (impostor) {
  72375. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  72376. if (!impostorForceAndContactPoint) {
  72377. return;
  72378. }
  72379. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72380. });
  72381. event.dispose(false);
  72382. return event;
  72383. };
  72384. /**
  72385. * @param {Vector3} origin the origin of the explosion
  72386. * @param {number} radius the explosion radius
  72387. * @param {number} strength the explosion strength
  72388. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  72389. */
  72390. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  72391. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  72392. if (!this._physicsEngine) {
  72393. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72394. return null;
  72395. }
  72396. var impostors = this._physicsEngine.getImpostors();
  72397. if (impostors.length === 0) {
  72398. return null;
  72399. }
  72400. var event = new PhysicsRadialExplosionEvent(this._scene);
  72401. impostors.forEach(function (impostor) {
  72402. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  72403. if (!impostorForceAndContactPoint) {
  72404. return;
  72405. }
  72406. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72407. });
  72408. event.dispose(false);
  72409. return event;
  72410. };
  72411. /**
  72412. * @param {Vector3} origin the origin of the explosion
  72413. * @param {number} radius the explosion radius
  72414. * @param {number} strength the explosion strength
  72415. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  72416. */
  72417. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  72418. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  72419. if (!this._physicsEngine) {
  72420. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72421. return null;
  72422. }
  72423. var impostors = this._physicsEngine.getImpostors();
  72424. if (impostors.length === 0) {
  72425. return null;
  72426. }
  72427. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  72428. event.dispose(false);
  72429. return event;
  72430. };
  72431. /**
  72432. * @param {Vector3} origin the origin of the updraft
  72433. * @param {number} radius the radius of the updraft
  72434. * @param {number} strength the strength of the updraft
  72435. * @param {number} height the height of the updraft
  72436. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  72437. */
  72438. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  72439. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  72440. if (!this._physicsEngine) {
  72441. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72442. return null;
  72443. }
  72444. if (this._physicsEngine.getImpostors().length === 0) {
  72445. return null;
  72446. }
  72447. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  72448. event.dispose(false);
  72449. return event;
  72450. };
  72451. /**
  72452. * @param {Vector3} origin the of the vortex
  72453. * @param {number} radius the radius of the vortex
  72454. * @param {number} strength the strength of the vortex
  72455. * @param {number} height the height of the vortex
  72456. */
  72457. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  72458. if (!this._physicsEngine) {
  72459. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  72460. return null;
  72461. }
  72462. if (this._physicsEngine.getImpostors().length === 0) {
  72463. return null;
  72464. }
  72465. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  72466. event.dispose(false);
  72467. return event;
  72468. };
  72469. return PhysicsHelper;
  72470. }());
  72471. BABYLON.PhysicsHelper = PhysicsHelper;
  72472. /***** Radial explosion *****/
  72473. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  72474. function PhysicsRadialExplosionEvent(scene) {
  72475. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  72476. this._rays = [];
  72477. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  72478. this._scene = scene;
  72479. }
  72480. /**
  72481. * Returns the data related to the radial explosion event (sphere & rays).
  72482. * @returns {PhysicsRadialExplosionEventData}
  72483. */
  72484. PhysicsRadialExplosionEvent.prototype.getData = function () {
  72485. this._dataFetched = true;
  72486. return {
  72487. sphere: this._sphere,
  72488. rays: this._rays,
  72489. };
  72490. };
  72491. /**
  72492. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  72493. * @param impostor
  72494. * @param {Vector3} origin the origin of the explosion
  72495. * @param {number} radius the explosion radius
  72496. * @param {number} strength the explosion strength
  72497. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  72498. * @returns {Nullable<PhysicsForceAndContactPoint>}
  72499. */
  72500. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  72501. if (impostor.mass === 0) {
  72502. return null;
  72503. }
  72504. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  72505. return null;
  72506. }
  72507. if (impostor.object.getClassName() !== 'Mesh') {
  72508. return null;
  72509. }
  72510. var impostorObject = impostor.object;
  72511. var impostorObjectCenter = impostor.getObjectCenter();
  72512. var direction = impostorObjectCenter.subtract(origin);
  72513. var ray = new BABYLON.Ray(origin, direction, radius);
  72514. this._rays.push(ray);
  72515. var hit = ray.intersectsMesh(impostorObject);
  72516. var contactPoint = hit.pickedPoint;
  72517. if (!contactPoint) {
  72518. return null;
  72519. }
  72520. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  72521. if (distanceFromOrigin > radius) {
  72522. return null;
  72523. }
  72524. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  72525. ? strength
  72526. : strength * (1 - (distanceFromOrigin / radius));
  72527. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  72528. return { force: force, contactPoint: contactPoint };
  72529. };
  72530. /**
  72531. * Disposes the sphere.
  72532. * @param {bolean} force
  72533. */
  72534. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  72535. var _this = this;
  72536. if (force === void 0) { force = true; }
  72537. if (force) {
  72538. this._sphere.dispose();
  72539. }
  72540. else {
  72541. setTimeout(function () {
  72542. if (!_this._dataFetched) {
  72543. _this._sphere.dispose();
  72544. }
  72545. }, 0);
  72546. }
  72547. };
  72548. /*** Helpers ***/
  72549. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  72550. if (!this._sphere) {
  72551. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  72552. this._sphere.isVisible = false;
  72553. }
  72554. };
  72555. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  72556. var impostorObject = impostor.object;
  72557. this._prepareSphere();
  72558. this._sphere.position = origin;
  72559. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  72560. this._sphere._updateBoundingInfo();
  72561. this._sphere.computeWorldMatrix(true);
  72562. return this._sphere.intersectsMesh(impostorObject, true);
  72563. };
  72564. return PhysicsRadialExplosionEvent;
  72565. }());
  72566. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  72567. /***** Gravitational Field *****/
  72568. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  72569. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  72570. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  72571. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72572. this._physicsHelper = physicsHelper;
  72573. this._scene = scene;
  72574. this._origin = origin;
  72575. this._radius = radius;
  72576. this._strength = strength;
  72577. this._falloff = falloff;
  72578. this._tickCallback = this._tick.bind(this);
  72579. }
  72580. /**
  72581. * Returns the data related to the gravitational field event (sphere).
  72582. * @returns {PhysicsGravitationalFieldEventData}
  72583. */
  72584. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  72585. this._dataFetched = true;
  72586. return {
  72587. sphere: this._sphere,
  72588. };
  72589. };
  72590. /**
  72591. * Enables the gravitational field.
  72592. */
  72593. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  72594. this._tickCallback.call(this);
  72595. this._scene.registerBeforeRender(this._tickCallback);
  72596. };
  72597. /**
  72598. * Disables the gravitational field.
  72599. */
  72600. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  72601. this._scene.unregisterBeforeRender(this._tickCallback);
  72602. };
  72603. /**
  72604. * Disposes the sphere.
  72605. * @param {bolean} force
  72606. */
  72607. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  72608. var _this = this;
  72609. if (force === void 0) { force = true; }
  72610. if (force) {
  72611. this._sphere.dispose();
  72612. }
  72613. else {
  72614. setTimeout(function () {
  72615. if (!_this._dataFetched) {
  72616. _this._sphere.dispose();
  72617. }
  72618. }, 0);
  72619. }
  72620. };
  72621. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  72622. // Since the params won't change, we fetch the event only once
  72623. if (this._sphere) {
  72624. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  72625. }
  72626. else {
  72627. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  72628. if (radialExplosionEvent) {
  72629. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  72630. }
  72631. }
  72632. };
  72633. return PhysicsGravitationalFieldEvent;
  72634. }());
  72635. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  72636. /***** Updraft *****/
  72637. var PhysicsUpdraftEvent = /** @class */ (function () {
  72638. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  72639. this._scene = _scene;
  72640. this._origin = _origin;
  72641. this._radius = _radius;
  72642. this._strength = _strength;
  72643. this._height = _height;
  72644. this._updraftMode = _updraftMode;
  72645. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  72646. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  72647. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  72648. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72649. this._physicsEngine = this._scene.getPhysicsEngine();
  72650. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  72651. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  72652. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  72653. this._originDirection = this._origin.subtract(this._originTop).normalize();
  72654. }
  72655. this._tickCallback = this._tick.bind(this);
  72656. }
  72657. /**
  72658. * Returns the data related to the updraft event (cylinder).
  72659. * @returns {PhysicsUpdraftEventData}
  72660. */
  72661. PhysicsUpdraftEvent.prototype.getData = function () {
  72662. this._dataFetched = true;
  72663. return {
  72664. cylinder: this._cylinder,
  72665. };
  72666. };
  72667. /**
  72668. * Enables the updraft.
  72669. */
  72670. PhysicsUpdraftEvent.prototype.enable = function () {
  72671. this._tickCallback.call(this);
  72672. this._scene.registerBeforeRender(this._tickCallback);
  72673. };
  72674. /**
  72675. * Disables the cortex.
  72676. */
  72677. PhysicsUpdraftEvent.prototype.disable = function () {
  72678. this._scene.unregisterBeforeRender(this._tickCallback);
  72679. };
  72680. /**
  72681. * Disposes the sphere.
  72682. * @param {bolean} force
  72683. */
  72684. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  72685. var _this = this;
  72686. if (force === void 0) { force = true; }
  72687. if (force) {
  72688. this._cylinder.dispose();
  72689. }
  72690. else {
  72691. setTimeout(function () {
  72692. if (!_this._dataFetched) {
  72693. _this._cylinder.dispose();
  72694. }
  72695. }, 0);
  72696. }
  72697. };
  72698. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72699. if (impostor.mass === 0) {
  72700. return null;
  72701. }
  72702. if (!this._intersectsWithCylinder(impostor)) {
  72703. return null;
  72704. }
  72705. var impostorObjectCenter = impostor.getObjectCenter();
  72706. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  72707. var direction = this._originDirection;
  72708. }
  72709. else {
  72710. var direction = impostorObjectCenter.subtract(this._originTop);
  72711. }
  72712. var multiplier = this._strength * -1;
  72713. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  72714. return { force: force, contactPoint: impostorObjectCenter };
  72715. };
  72716. PhysicsUpdraftEvent.prototype._tick = function () {
  72717. var _this = this;
  72718. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72719. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72720. if (!impostorForceAndContactPoint) {
  72721. return;
  72722. }
  72723. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72724. });
  72725. };
  72726. /*** Helpers ***/
  72727. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  72728. if (!this._cylinder) {
  72729. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  72730. height: this._height,
  72731. diameter: this._radius * 2,
  72732. }, this._scene);
  72733. this._cylinder.isVisible = false;
  72734. }
  72735. };
  72736. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  72737. var impostorObject = impostor.object;
  72738. this._prepareCylinder();
  72739. this._cylinder.position = this._cylinderPosition;
  72740. return this._cylinder.intersectsMesh(impostorObject, true);
  72741. };
  72742. return PhysicsUpdraftEvent;
  72743. }());
  72744. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  72745. /***** Vortex *****/
  72746. var PhysicsVortexEvent = /** @class */ (function () {
  72747. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  72748. this._scene = _scene;
  72749. this._origin = _origin;
  72750. this._radius = _radius;
  72751. this._strength = _strength;
  72752. this._height = _height;
  72753. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  72754. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  72755. this._updraftMultiplier = 0.02;
  72756. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  72757. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72758. this._physicsEngine = this._scene.getPhysicsEngine();
  72759. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  72760. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  72761. this._tickCallback = this._tick.bind(this);
  72762. }
  72763. /**
  72764. * Returns the data related to the vortex event (cylinder).
  72765. * @returns {PhysicsVortexEventData}
  72766. */
  72767. PhysicsVortexEvent.prototype.getData = function () {
  72768. this._dataFetched = true;
  72769. return {
  72770. cylinder: this._cylinder,
  72771. };
  72772. };
  72773. /**
  72774. * Enables the vortex.
  72775. */
  72776. PhysicsVortexEvent.prototype.enable = function () {
  72777. this._tickCallback.call(this);
  72778. this._scene.registerBeforeRender(this._tickCallback);
  72779. };
  72780. /**
  72781. * Disables the cortex.
  72782. */
  72783. PhysicsVortexEvent.prototype.disable = function () {
  72784. this._scene.unregisterBeforeRender(this._tickCallback);
  72785. };
  72786. /**
  72787. * Disposes the sphere.
  72788. * @param {bolean} force
  72789. */
  72790. PhysicsVortexEvent.prototype.dispose = function (force) {
  72791. var _this = this;
  72792. if (force === void 0) { force = true; }
  72793. if (force) {
  72794. this._cylinder.dispose();
  72795. }
  72796. else {
  72797. setTimeout(function () {
  72798. if (!_this._dataFetched) {
  72799. _this._cylinder.dispose();
  72800. }
  72801. }, 0);
  72802. }
  72803. };
  72804. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72805. if (impostor.mass === 0) {
  72806. return null;
  72807. }
  72808. if (!this._intersectsWithCylinder(impostor)) {
  72809. return null;
  72810. }
  72811. if (impostor.object.getClassName() !== 'Mesh') {
  72812. return null;
  72813. }
  72814. var impostorObject = impostor.object;
  72815. var impostorObjectCenter = impostor.getObjectCenter();
  72816. 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)
  72817. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  72818. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  72819. var hit = ray.intersectsMesh(impostorObject);
  72820. var contactPoint = hit.pickedPoint;
  72821. if (!contactPoint) {
  72822. return null;
  72823. }
  72824. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  72825. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  72826. var directionToOrigin = contactPoint.normalize();
  72827. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72828. directionToOrigin = directionToOrigin.negate();
  72829. }
  72830. // TODO: find a more physically based solution
  72831. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72832. var forceX = directionToOrigin.x * this._strength / 8;
  72833. var forceY = directionToOrigin.y * this._updraftMultiplier;
  72834. var forceZ = directionToOrigin.z * this._strength / 8;
  72835. }
  72836. else {
  72837. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  72838. var forceY = this._originTop.y * this._updraftMultiplier;
  72839. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  72840. }
  72841. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  72842. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  72843. return { force: force, contactPoint: impostorObjectCenter };
  72844. };
  72845. PhysicsVortexEvent.prototype._tick = function () {
  72846. var _this = this;
  72847. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72848. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72849. if (!impostorForceAndContactPoint) {
  72850. return;
  72851. }
  72852. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72853. });
  72854. };
  72855. /*** Helpers ***/
  72856. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  72857. if (!this._cylinder) {
  72858. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  72859. height: this._height,
  72860. diameter: this._radius * 2,
  72861. }, this._scene);
  72862. this._cylinder.isVisible = false;
  72863. }
  72864. };
  72865. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  72866. var impostorObject = impostor.object;
  72867. this._prepareCylinder();
  72868. this._cylinder.position = this._cylinderPosition;
  72869. return this._cylinder.intersectsMesh(impostorObject, true);
  72870. };
  72871. return PhysicsVortexEvent;
  72872. }());
  72873. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  72874. /***** Enums *****/
  72875. /**
  72876. * The strenght of the force in correspondence to the distance of the affected object
  72877. */
  72878. var PhysicsRadialImpulseFalloff;
  72879. (function (PhysicsRadialImpulseFalloff) {
  72880. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  72881. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  72882. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  72883. /**
  72884. * The strenght of the force in correspondence to the distance of the affected object
  72885. */
  72886. var PhysicsUpdraftMode;
  72887. (function (PhysicsUpdraftMode) {
  72888. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  72889. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  72890. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  72891. })(BABYLON || (BABYLON = {}));
  72892. //# sourceMappingURL=babylon.physicsHelper.js.map
  72893. var BABYLON;
  72894. (function (BABYLON) {
  72895. var CannonJSPlugin = /** @class */ (function () {
  72896. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  72897. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  72898. if (iterations === void 0) { iterations = 10; }
  72899. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  72900. this.name = "CannonJSPlugin";
  72901. this._physicsMaterials = new Array();
  72902. this._fixedTimeStep = 1 / 60;
  72903. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  72904. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  72905. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  72906. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  72907. this._tmpPosition = BABYLON.Vector3.Zero();
  72908. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  72909. this._tmpUnityRotation = new BABYLON.Quaternion();
  72910. if (!this.isSupported()) {
  72911. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  72912. return;
  72913. }
  72914. this._extendNamespace();
  72915. this.world = new this.BJSCANNON.World();
  72916. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  72917. this.world.solver.iterations = iterations;
  72918. }
  72919. CannonJSPlugin.prototype.setGravity = function (gravity) {
  72920. this.world.gravity.copy(gravity);
  72921. };
  72922. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  72923. this._fixedTimeStep = timeStep;
  72924. };
  72925. CannonJSPlugin.prototype.getTimeStep = function () {
  72926. return this._fixedTimeStep;
  72927. };
  72928. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  72929. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  72930. };
  72931. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  72932. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72933. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72934. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  72935. };
  72936. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  72937. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72938. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72939. impostor.physicsBody.applyForce(impulse, worldPoint);
  72940. };
  72941. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  72942. //parent-child relationship. Does this impostor has a parent impostor?
  72943. if (impostor.parent) {
  72944. if (impostor.physicsBody) {
  72945. this.removePhysicsBody(impostor);
  72946. //TODO is that needed?
  72947. impostor.forceUpdate();
  72948. }
  72949. return;
  72950. }
  72951. //should a new body be created for this impostor?
  72952. if (impostor.isBodyInitRequired()) {
  72953. var shape = this._createShape(impostor);
  72954. //unregister events, if body is being changed
  72955. var oldBody = impostor.physicsBody;
  72956. if (oldBody) {
  72957. this.removePhysicsBody(impostor);
  72958. }
  72959. //create the body and material
  72960. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  72961. var bodyCreationObject = {
  72962. mass: impostor.getParam("mass"),
  72963. material: material
  72964. };
  72965. // A simple extend, in case native options were used.
  72966. var nativeOptions = impostor.getParam("nativeOptions");
  72967. for (var key in nativeOptions) {
  72968. if (nativeOptions.hasOwnProperty(key)) {
  72969. bodyCreationObject[key] = nativeOptions[key];
  72970. }
  72971. }
  72972. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  72973. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  72974. this.world.addEventListener("preStep", impostor.beforeStep);
  72975. this.world.addEventListener("postStep", impostor.afterStep);
  72976. impostor.physicsBody.addShape(shape);
  72977. this.world.add(impostor.physicsBody);
  72978. //try to keep the body moving in the right direction by taking old properties.
  72979. //Should be tested!
  72980. if (oldBody) {
  72981. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  72982. impostor.physicsBody[param].copy(oldBody[param]);
  72983. });
  72984. }
  72985. this._processChildMeshes(impostor);
  72986. }
  72987. //now update the body's transformation
  72988. this._updatePhysicsBodyTransformation(impostor);
  72989. };
  72990. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  72991. var _this = this;
  72992. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  72993. var currentRotation = mainImpostor.object.rotationQuaternion;
  72994. if (meshChildren.length) {
  72995. var processMesh = function (localPosition, mesh) {
  72996. if (!currentRotation || !mesh.rotationQuaternion) {
  72997. return;
  72998. }
  72999. var childImpostor = mesh.getPhysicsImpostor();
  73000. if (childImpostor) {
  73001. var parent = childImpostor.parent;
  73002. if (parent !== mainImpostor) {
  73003. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  73004. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  73005. if (childImpostor.physicsBody) {
  73006. _this.removePhysicsBody(childImpostor);
  73007. childImpostor.physicsBody = null;
  73008. }
  73009. childImpostor.parent = mainImpostor;
  73010. childImpostor.resetUpdateFlags();
  73011. 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));
  73012. //Add the mass of the children.
  73013. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  73014. }
  73015. }
  73016. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  73017. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  73018. };
  73019. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  73020. }
  73021. };
  73022. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  73023. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  73024. this.world.removeEventListener("preStep", impostor.beforeStep);
  73025. this.world.removeEventListener("postStep", impostor.afterStep);
  73026. this.world.remove(impostor.physicsBody);
  73027. };
  73028. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  73029. var mainBody = impostorJoint.mainImpostor.physicsBody;
  73030. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  73031. if (!mainBody || !connectedBody) {
  73032. return;
  73033. }
  73034. var constraint;
  73035. var jointData = impostorJoint.joint.jointData;
  73036. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  73037. var constraintData = {
  73038. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  73039. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  73040. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  73041. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  73042. maxForce: jointData.nativeParams.maxForce,
  73043. collideConnected: !!jointData.collision
  73044. };
  73045. switch (impostorJoint.joint.type) {
  73046. case BABYLON.PhysicsJoint.HingeJoint:
  73047. case BABYLON.PhysicsJoint.Hinge2Joint:
  73048. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  73049. break;
  73050. case BABYLON.PhysicsJoint.DistanceJoint:
  73051. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  73052. break;
  73053. case BABYLON.PhysicsJoint.SpringJoint:
  73054. var springData = jointData;
  73055. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  73056. restLength: springData.length,
  73057. stiffness: springData.stiffness,
  73058. damping: springData.damping,
  73059. localAnchorA: constraintData.pivotA,
  73060. localAnchorB: constraintData.pivotB
  73061. });
  73062. break;
  73063. case BABYLON.PhysicsJoint.LockJoint:
  73064. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  73065. break;
  73066. case BABYLON.PhysicsJoint.PointToPointJoint:
  73067. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  73068. default:
  73069. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  73070. break;
  73071. }
  73072. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  73073. constraint.collideConnected = !!jointData.collision;
  73074. impostorJoint.joint.physicsJoint = constraint;
  73075. //don't add spring as constraint, as it is not one.
  73076. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  73077. this.world.addConstraint(constraint);
  73078. }
  73079. else {
  73080. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  73081. constraint.applyForce();
  73082. });
  73083. }
  73084. };
  73085. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  73086. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  73087. };
  73088. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  73089. var index;
  73090. var mat;
  73091. for (index = 0; index < this._physicsMaterials.length; index++) {
  73092. mat = this._physicsMaterials[index];
  73093. if (mat.friction === friction && mat.restitution === restitution) {
  73094. return mat;
  73095. }
  73096. }
  73097. var currentMat = new this.BJSCANNON.Material(name);
  73098. currentMat.friction = friction;
  73099. currentMat.restitution = restitution;
  73100. this._physicsMaterials.push(currentMat);
  73101. return currentMat;
  73102. };
  73103. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  73104. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  73105. };
  73106. CannonJSPlugin.prototype._createShape = function (impostor) {
  73107. var object = impostor.object;
  73108. var returnValue;
  73109. var extendSize = impostor.getObjectExtendSize();
  73110. switch (impostor.type) {
  73111. case BABYLON.PhysicsImpostor.SphereImpostor:
  73112. var radiusX = extendSize.x;
  73113. var radiusY = extendSize.y;
  73114. var radiusZ = extendSize.z;
  73115. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  73116. break;
  73117. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  73118. case BABYLON.PhysicsImpostor.CylinderImpostor:
  73119. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  73120. break;
  73121. case BABYLON.PhysicsImpostor.BoxImpostor:
  73122. var box = extendSize.scale(0.5);
  73123. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  73124. break;
  73125. case BABYLON.PhysicsImpostor.PlaneImpostor:
  73126. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  73127. returnValue = new this.BJSCANNON.Plane();
  73128. break;
  73129. case BABYLON.PhysicsImpostor.MeshImpostor:
  73130. // should transform the vertex data to world coordinates!!
  73131. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  73132. var rawFaces = object.getIndices ? object.getIndices() : [];
  73133. if (!rawVerts)
  73134. return;
  73135. // get only scale! so the object could transform correctly.
  73136. var oldPosition = object.position.clone();
  73137. var oldRotation = object.rotation && object.rotation.clone();
  73138. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  73139. object.position.copyFromFloats(0, 0, 0);
  73140. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  73141. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  73142. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  73143. var transform = object.computeWorldMatrix(true);
  73144. // convert rawVerts to object space
  73145. var temp = new Array();
  73146. var index;
  73147. for (index = 0; index < rawVerts.length; index += 3) {
  73148. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  73149. }
  73150. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  73151. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  73152. //now set back the transformation!
  73153. object.position.copyFrom(oldPosition);
  73154. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  73155. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  73156. break;
  73157. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  73158. var oldPosition2 = object.position.clone();
  73159. var oldRotation2 = object.rotation && object.rotation.clone();
  73160. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  73161. object.position.copyFromFloats(0, 0, 0);
  73162. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  73163. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  73164. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  73165. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  73166. returnValue = this._createHeightmap(object);
  73167. object.position.copyFrom(oldPosition2);
  73168. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  73169. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  73170. object.computeWorldMatrix(true);
  73171. break;
  73172. case BABYLON.PhysicsImpostor.ParticleImpostor:
  73173. returnValue = new this.BJSCANNON.Particle();
  73174. break;
  73175. }
  73176. return returnValue;
  73177. };
  73178. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  73179. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  73180. var transform = object.computeWorldMatrix(true);
  73181. // convert rawVerts to object space
  73182. var temp = new Array();
  73183. var index;
  73184. for (index = 0; index < pos.length; index += 3) {
  73185. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  73186. }
  73187. pos = temp;
  73188. var matrix = new Array();
  73189. //For now pointDepth will not be used and will be automatically calculated.
  73190. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  73191. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  73192. var boundingInfo = object.getBoundingInfo();
  73193. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  73194. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  73195. var elementSize = dim * 2 / arraySize;
  73196. for (var i = 0; i < pos.length; i = i + 3) {
  73197. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  73198. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  73199. var y = -pos[i + 2] + minY;
  73200. if (!matrix[x]) {
  73201. matrix[x] = [];
  73202. }
  73203. if (!matrix[x][z]) {
  73204. matrix[x][z] = y;
  73205. }
  73206. matrix[x][z] = Math.max(y, matrix[x][z]);
  73207. }
  73208. for (var x = 0; x <= arraySize; ++x) {
  73209. if (!matrix[x]) {
  73210. var loc = 1;
  73211. while (!matrix[(x + loc) % arraySize]) {
  73212. loc++;
  73213. }
  73214. matrix[x] = matrix[(x + loc) % arraySize].slice();
  73215. //console.log("missing x", x);
  73216. }
  73217. for (var z = 0; z <= arraySize; ++z) {
  73218. if (!matrix[x][z]) {
  73219. var loc = 1;
  73220. var newValue;
  73221. while (newValue === undefined) {
  73222. newValue = matrix[x][(z + loc++) % arraySize];
  73223. }
  73224. matrix[x][z] = newValue;
  73225. }
  73226. }
  73227. }
  73228. var shape = new this.BJSCANNON.Heightfield(matrix, {
  73229. elementSize: elementSize
  73230. });
  73231. //For future reference, needed for body transformation
  73232. shape.minY = minY;
  73233. return shape;
  73234. };
  73235. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  73236. var object = impostor.object;
  73237. //make sure it is updated...
  73238. object.computeWorldMatrix && object.computeWorldMatrix(true);
  73239. // The delta between the mesh position and the mesh bounding box center
  73240. var bInfo = object.getBoundingInfo();
  73241. if (!bInfo)
  73242. return;
  73243. var center = impostor.getObjectCenter();
  73244. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  73245. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  73246. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  73247. this._tmpPosition.copyFrom(center);
  73248. var quaternion = object.rotationQuaternion;
  73249. if (!quaternion) {
  73250. return;
  73251. }
  73252. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  73253. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  73254. //-90 DEG in X, precalculated
  73255. quaternion = quaternion.multiply(this._minus90X);
  73256. //Invert! (Precalculated, 90 deg in X)
  73257. //No need to clone. this will never change.
  73258. impostor.setDeltaRotation(this._plus90X);
  73259. }
  73260. //If it is a heightfield, if should be centered.
  73261. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  73262. var mesh = object;
  73263. var boundingInfo = mesh.getBoundingInfo();
  73264. //calculate the correct body position:
  73265. var rotationQuaternion = mesh.rotationQuaternion;
  73266. mesh.rotationQuaternion = this._tmpUnityRotation;
  73267. mesh.computeWorldMatrix(true);
  73268. //get original center with no rotation
  73269. var c = center.clone();
  73270. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  73271. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  73272. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  73273. mesh.setPivotMatrix(p);
  73274. mesh.computeWorldMatrix(true);
  73275. //calculate the translation
  73276. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  73277. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  73278. //add it inverted to the delta
  73279. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  73280. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  73281. //rotation is back
  73282. mesh.rotationQuaternion = rotationQuaternion;
  73283. mesh.setPivotMatrix(oldPivot);
  73284. mesh.computeWorldMatrix(true);
  73285. }
  73286. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  73287. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  73288. //this._tmpPosition.copyFrom(object.position);
  73289. }
  73290. impostor.setDeltaPosition(this._tmpDeltaPosition);
  73291. //Now update the impostor object
  73292. impostor.physicsBody.position.copy(this._tmpPosition);
  73293. impostor.physicsBody.quaternion.copy(quaternion);
  73294. };
  73295. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  73296. impostor.object.position.copyFrom(impostor.physicsBody.position);
  73297. if (impostor.object.rotationQuaternion) {
  73298. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  73299. }
  73300. };
  73301. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  73302. impostor.physicsBody.position.copy(newPosition);
  73303. impostor.physicsBody.quaternion.copy(newRotation);
  73304. };
  73305. CannonJSPlugin.prototype.isSupported = function () {
  73306. return this.BJSCANNON !== undefined;
  73307. };
  73308. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  73309. impostor.physicsBody.velocity.copy(velocity);
  73310. };
  73311. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  73312. impostor.physicsBody.angularVelocity.copy(velocity);
  73313. };
  73314. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  73315. var v = impostor.physicsBody.velocity;
  73316. if (!v) {
  73317. return null;
  73318. }
  73319. return new BABYLON.Vector3(v.x, v.y, v.z);
  73320. };
  73321. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  73322. var v = impostor.physicsBody.angularVelocity;
  73323. if (!v) {
  73324. return null;
  73325. }
  73326. return new BABYLON.Vector3(v.x, v.y, v.z);
  73327. };
  73328. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  73329. impostor.physicsBody.mass = mass;
  73330. impostor.physicsBody.updateMassProperties();
  73331. };
  73332. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  73333. return impostor.physicsBody.mass;
  73334. };
  73335. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  73336. return impostor.physicsBody.material.friction;
  73337. };
  73338. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  73339. impostor.physicsBody.material.friction = friction;
  73340. };
  73341. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  73342. return impostor.physicsBody.material.restitution;
  73343. };
  73344. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  73345. impostor.physicsBody.material.restitution = restitution;
  73346. };
  73347. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  73348. impostor.physicsBody.sleep();
  73349. };
  73350. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  73351. impostor.physicsBody.wakeUp();
  73352. };
  73353. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  73354. joint.physicsJoint.distance = maxDistance;
  73355. };
  73356. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  73357. // if (!motorIndex) {
  73358. // joint.physicsJoint.enableMotor();
  73359. // }
  73360. // }
  73361. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  73362. // if (!motorIndex) {
  73363. // joint.physicsJoint.disableMotor();
  73364. // }
  73365. // }
  73366. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  73367. if (!motorIndex) {
  73368. joint.physicsJoint.enableMotor();
  73369. joint.physicsJoint.setMotorSpeed(speed);
  73370. if (maxForce) {
  73371. this.setLimit(joint, maxForce);
  73372. }
  73373. }
  73374. };
  73375. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  73376. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  73377. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  73378. };
  73379. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  73380. var body = impostor.physicsBody;
  73381. mesh.position.x = body.position.x;
  73382. mesh.position.y = body.position.y;
  73383. mesh.position.z = body.position.z;
  73384. if (mesh.rotationQuaternion) {
  73385. mesh.rotationQuaternion.x = body.quaternion.x;
  73386. mesh.rotationQuaternion.y = body.quaternion.y;
  73387. mesh.rotationQuaternion.z = body.quaternion.z;
  73388. mesh.rotationQuaternion.w = body.quaternion.w;
  73389. }
  73390. };
  73391. CannonJSPlugin.prototype.getRadius = function (impostor) {
  73392. var shape = impostor.physicsBody.shapes[0];
  73393. return shape.boundingSphereRadius;
  73394. };
  73395. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  73396. var shape = impostor.physicsBody.shapes[0];
  73397. result.x = shape.halfExtents.x * 2;
  73398. result.y = shape.halfExtents.y * 2;
  73399. result.z = shape.halfExtents.z * 2;
  73400. };
  73401. CannonJSPlugin.prototype.dispose = function () {
  73402. };
  73403. CannonJSPlugin.prototype._extendNamespace = function () {
  73404. //this will force cannon to execute at least one step when using interpolation
  73405. var step_tmp1 = new this.BJSCANNON.Vec3();
  73406. var Engine = this.BJSCANNON;
  73407. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  73408. maxSubSteps = maxSubSteps || 10;
  73409. timeSinceLastCalled = timeSinceLastCalled || 0;
  73410. if (timeSinceLastCalled === 0) {
  73411. this.internalStep(dt);
  73412. this.time += dt;
  73413. }
  73414. else {
  73415. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  73416. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  73417. var t0 = performance.now();
  73418. for (var i = 0; i !== internalSteps; i++) {
  73419. this.internalStep(dt);
  73420. if (performance.now() - t0 > dt * 1000) {
  73421. break;
  73422. }
  73423. }
  73424. this.time += timeSinceLastCalled;
  73425. var h = this.time % dt;
  73426. var h_div_dt = h / dt;
  73427. var interpvelo = step_tmp1;
  73428. var bodies = this.bodies;
  73429. for (var j = 0; j !== bodies.length; j++) {
  73430. var b = bodies[j];
  73431. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  73432. b.position.vsub(b.previousPosition, interpvelo);
  73433. interpvelo.scale(h_div_dt, interpvelo);
  73434. b.position.vadd(interpvelo, b.interpolatedPosition);
  73435. }
  73436. else {
  73437. b.interpolatedPosition.copy(b.position);
  73438. b.interpolatedQuaternion.copy(b.quaternion);
  73439. }
  73440. }
  73441. }
  73442. };
  73443. };
  73444. return CannonJSPlugin;
  73445. }());
  73446. BABYLON.CannonJSPlugin = CannonJSPlugin;
  73447. })(BABYLON || (BABYLON = {}));
  73448. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  73449. var BABYLON;
  73450. (function (BABYLON) {
  73451. var OimoJSPlugin = /** @class */ (function () {
  73452. function OimoJSPlugin(iterations) {
  73453. this.name = "OimoJSPlugin";
  73454. this._tmpImpostorsArray = [];
  73455. this._tmpPositionVector = BABYLON.Vector3.Zero();
  73456. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  73457. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  73458. this.world.worldscale(1);
  73459. this.world.clear();
  73460. //making sure no stats are calculated
  73461. this.world.isNoStat = true;
  73462. }
  73463. OimoJSPlugin.prototype.setGravity = function (gravity) {
  73464. this.world.gravity.copy(gravity);
  73465. };
  73466. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  73467. this.world.timeStep = timeStep;
  73468. };
  73469. OimoJSPlugin.prototype.getTimeStep = function () {
  73470. return this.world.timeStep;
  73471. };
  73472. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  73473. var _this = this;
  73474. impostors.forEach(function (impostor) {
  73475. impostor.beforeStep();
  73476. });
  73477. this.world.step();
  73478. impostors.forEach(function (impostor) {
  73479. impostor.afterStep();
  73480. //update the ordered impostors array
  73481. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  73482. });
  73483. //check for collisions
  73484. var contact = this.world.contacts;
  73485. while (contact !== null) {
  73486. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  73487. contact = contact.next;
  73488. continue;
  73489. }
  73490. //is this body colliding with any other? get the impostor
  73491. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  73492. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  73493. if (!mainImpostor || !collidingImpostor) {
  73494. contact = contact.next;
  73495. continue;
  73496. }
  73497. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  73498. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  73499. contact = contact.next;
  73500. }
  73501. };
  73502. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  73503. var mass = impostor.physicsBody.massInfo.mass;
  73504. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  73505. };
  73506. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  73507. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  73508. this.applyImpulse(impostor, force, contactPoint);
  73509. };
  73510. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  73511. var _this = this;
  73512. //parent-child relationship. Does this impostor has a parent impostor?
  73513. if (impostor.parent) {
  73514. if (impostor.physicsBody) {
  73515. this.removePhysicsBody(impostor);
  73516. //TODO is that needed?
  73517. impostor.forceUpdate();
  73518. }
  73519. return;
  73520. }
  73521. if (impostor.isBodyInitRequired()) {
  73522. var bodyConfig = {
  73523. name: impostor.uniqueId,
  73524. //Oimo must have mass, also for static objects.
  73525. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  73526. size: [],
  73527. type: [],
  73528. pos: [],
  73529. rot: [],
  73530. move: impostor.getParam("mass") !== 0,
  73531. //Supporting older versions of Oimo
  73532. world: this.world
  73533. };
  73534. var impostors = [impostor];
  73535. var addToArray = function (parent) {
  73536. if (!parent.getChildMeshes)
  73537. return;
  73538. parent.getChildMeshes().forEach(function (m) {
  73539. if (m.physicsImpostor) {
  73540. impostors.push(m.physicsImpostor);
  73541. //m.physicsImpostor._init();
  73542. }
  73543. });
  73544. };
  73545. addToArray(impostor.object);
  73546. var checkWithEpsilon_1 = function (value) {
  73547. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  73548. };
  73549. impostors.forEach(function (i) {
  73550. if (!impostor.object.rotationQuaternion) {
  73551. return;
  73552. }
  73553. //get the correct bounding box
  73554. var oldQuaternion = i.object.rotationQuaternion;
  73555. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  73556. x: impostor.object.rotationQuaternion.x,
  73557. y: impostor.object.rotationQuaternion.y,
  73558. z: impostor.object.rotationQuaternion.z,
  73559. s: impostor.object.rotationQuaternion.w
  73560. });
  73561. var extendSize = i.getObjectExtendSize();
  73562. if (i === impostor) {
  73563. var center = impostor.getObjectCenter();
  73564. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  73565. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  73566. //Can also use Array.prototype.push.apply
  73567. bodyConfig.pos.push(center.x);
  73568. bodyConfig.pos.push(center.y);
  73569. bodyConfig.pos.push(center.z);
  73570. //tmp solution
  73571. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  73572. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  73573. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  73574. }
  73575. else {
  73576. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  73577. bodyConfig.pos.push(localPosition.x);
  73578. bodyConfig.pos.push(localPosition.y);
  73579. bodyConfig.pos.push(localPosition.z);
  73580. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  73581. bodyConfig.rot.push(0);
  73582. bodyConfig.rot.push(0);
  73583. bodyConfig.rot.push(0);
  73584. }
  73585. // register mesh
  73586. switch (i.type) {
  73587. case BABYLON.PhysicsImpostor.ParticleImpostor:
  73588. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  73589. case BABYLON.PhysicsImpostor.SphereImpostor:
  73590. var radiusX = extendSize.x;
  73591. var radiusY = extendSize.y;
  73592. var radiusZ = extendSize.z;
  73593. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  73594. bodyConfig.type.push('sphere');
  73595. //due to the way oimo works with compounds, add 3 times
  73596. bodyConfig.size.push(size);
  73597. bodyConfig.size.push(size);
  73598. bodyConfig.size.push(size);
  73599. break;
  73600. case BABYLON.PhysicsImpostor.CylinderImpostor:
  73601. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  73602. var sizeY = checkWithEpsilon_1(extendSize.y);
  73603. bodyConfig.type.push('cylinder');
  73604. bodyConfig.size.push(sizeX);
  73605. bodyConfig.size.push(sizeY);
  73606. //due to the way oimo works with compounds, add one more value.
  73607. bodyConfig.size.push(sizeY);
  73608. break;
  73609. case BABYLON.PhysicsImpostor.PlaneImpostor:
  73610. case BABYLON.PhysicsImpostor.BoxImpostor:
  73611. default:
  73612. var sizeX = checkWithEpsilon_1(extendSize.x);
  73613. var sizeY = checkWithEpsilon_1(extendSize.y);
  73614. var sizeZ = checkWithEpsilon_1(extendSize.z);
  73615. bodyConfig.type.push('box');
  73616. bodyConfig.size.push(sizeX);
  73617. bodyConfig.size.push(sizeY);
  73618. bodyConfig.size.push(sizeZ);
  73619. break;
  73620. }
  73621. //actually not needed, but hey...
  73622. i.object.rotationQuaternion = oldQuaternion;
  73623. });
  73624. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  73625. }
  73626. else {
  73627. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  73628. }
  73629. impostor.setDeltaPosition(this._tmpPositionVector);
  73630. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  73631. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  73632. };
  73633. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  73634. //impostor.physicsBody.dispose();
  73635. //Same as : (older oimo versions)
  73636. this.world.removeRigidBody(impostor.physicsBody);
  73637. };
  73638. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  73639. var mainBody = impostorJoint.mainImpostor.physicsBody;
  73640. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  73641. if (!mainBody || !connectedBody) {
  73642. return;
  73643. }
  73644. var jointData = impostorJoint.joint.jointData;
  73645. var options = jointData.nativeParams || {};
  73646. var type;
  73647. var nativeJointData = {
  73648. body1: mainBody,
  73649. body2: connectedBody,
  73650. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  73651. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  73652. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  73653. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  73654. min: options.min,
  73655. max: options.max,
  73656. collision: options.collision || jointData.collision,
  73657. spring: options.spring,
  73658. //supporting older version of Oimo
  73659. world: this.world
  73660. };
  73661. switch (impostorJoint.joint.type) {
  73662. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  73663. type = "jointBall";
  73664. break;
  73665. case BABYLON.PhysicsJoint.SpringJoint:
  73666. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  73667. var springData = jointData;
  73668. nativeJointData.min = springData.length || nativeJointData.min;
  73669. //Max should also be set, just make sure it is at least min
  73670. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  73671. case BABYLON.PhysicsJoint.DistanceJoint:
  73672. type = "jointDistance";
  73673. nativeJointData.max = jointData.maxDistance;
  73674. break;
  73675. case BABYLON.PhysicsJoint.PrismaticJoint:
  73676. type = "jointPrisme";
  73677. break;
  73678. case BABYLON.PhysicsJoint.SliderJoint:
  73679. type = "jointSlide";
  73680. break;
  73681. case BABYLON.PhysicsJoint.WheelJoint:
  73682. type = "jointWheel";
  73683. break;
  73684. case BABYLON.PhysicsJoint.HingeJoint:
  73685. default:
  73686. type = "jointHinge";
  73687. break;
  73688. }
  73689. nativeJointData.type = type;
  73690. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  73691. };
  73692. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  73693. //Bug in Oimo prevents us from disposing a joint in the playground
  73694. //joint.joint.physicsJoint.dispose();
  73695. //So we will bruteforce it!
  73696. try {
  73697. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  73698. }
  73699. catch (e) {
  73700. BABYLON.Tools.Warn(e);
  73701. }
  73702. };
  73703. OimoJSPlugin.prototype.isSupported = function () {
  73704. return this.BJSOIMO !== undefined;
  73705. };
  73706. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  73707. if (!impostor.physicsBody.sleeping) {
  73708. //TODO check that
  73709. if (impostor.physicsBody.shapes.next) {
  73710. var parentShape = this._getLastShape(impostor.physicsBody);
  73711. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  73712. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  73713. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  73714. }
  73715. else {
  73716. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  73717. }
  73718. if (impostor.object.rotationQuaternion) {
  73719. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  73720. impostor.object.rotationQuaternion.normalize();
  73721. }
  73722. }
  73723. };
  73724. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  73725. var body = impostor.physicsBody;
  73726. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  73727. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  73728. body.syncShapes();
  73729. body.awake();
  73730. };
  73731. OimoJSPlugin.prototype._getLastShape = function (body) {
  73732. var lastShape = body.shapes;
  73733. while (lastShape.next) {
  73734. lastShape = lastShape.next;
  73735. }
  73736. return lastShape;
  73737. };
  73738. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  73739. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  73740. };
  73741. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  73742. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  73743. };
  73744. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  73745. var v = impostor.physicsBody.linearVelocity;
  73746. if (!v) {
  73747. return null;
  73748. }
  73749. return new BABYLON.Vector3(v.x, v.y, v.z);
  73750. };
  73751. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  73752. var v = impostor.physicsBody.angularVelocity;
  73753. if (!v) {
  73754. return null;
  73755. }
  73756. return new BABYLON.Vector3(v.x, v.y, v.z);
  73757. };
  73758. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  73759. var staticBody = mass === 0;
  73760. //this will actually set the body's density and not its mass.
  73761. //But this is how oimo treats the mass variable.
  73762. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  73763. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  73764. };
  73765. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  73766. return impostor.physicsBody.shapes.density;
  73767. };
  73768. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  73769. return impostor.physicsBody.shapes.friction;
  73770. };
  73771. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  73772. impostor.physicsBody.shapes.friction = friction;
  73773. };
  73774. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  73775. return impostor.physicsBody.shapes.restitution;
  73776. };
  73777. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  73778. impostor.physicsBody.shapes.restitution = restitution;
  73779. };
  73780. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  73781. impostor.physicsBody.sleep();
  73782. };
  73783. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  73784. impostor.physicsBody.awake();
  73785. };
  73786. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  73787. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  73788. if (minDistance !== void 0) {
  73789. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  73790. }
  73791. };
  73792. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  73793. //TODO separate rotational and transational motors.
  73794. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73795. if (motor) {
  73796. motor.setMotor(speed, maxForce);
  73797. }
  73798. };
  73799. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  73800. //TODO separate rotational and transational motors.
  73801. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73802. if (motor) {
  73803. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  73804. }
  73805. };
  73806. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  73807. var body = impostor.physicsBody;
  73808. mesh.position.x = body.position.x;
  73809. mesh.position.y = body.position.y;
  73810. mesh.position.z = body.position.z;
  73811. if (mesh.rotationQuaternion) {
  73812. mesh.rotationQuaternion.x = body.orientation.x;
  73813. mesh.rotationQuaternion.y = body.orientation.y;
  73814. mesh.rotationQuaternion.z = body.orientation.z;
  73815. mesh.rotationQuaternion.w = body.orientation.s;
  73816. }
  73817. };
  73818. OimoJSPlugin.prototype.getRadius = function (impostor) {
  73819. return impostor.physicsBody.shapes.radius;
  73820. };
  73821. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  73822. var shape = impostor.physicsBody.shapes;
  73823. result.x = shape.halfWidth * 2;
  73824. result.y = shape.halfHeight * 2;
  73825. result.z = shape.halfDepth * 2;
  73826. };
  73827. OimoJSPlugin.prototype.dispose = function () {
  73828. this.world.clear();
  73829. };
  73830. return OimoJSPlugin;
  73831. }());
  73832. BABYLON.OimoJSPlugin = OimoJSPlugin;
  73833. })(BABYLON || (BABYLON = {}));
  73834. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  73835. var BABYLON;
  73836. (function (BABYLON) {
  73837. /*
  73838. * Based on jsTGALoader - Javascript loader for TGA file
  73839. * By Vincent Thibault
  73840. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  73841. */
  73842. var TGATools = /** @class */ (function () {
  73843. function TGATools() {
  73844. }
  73845. TGATools.GetTGAHeader = function (data) {
  73846. var offset = 0;
  73847. var header = {
  73848. id_length: data[offset++],
  73849. colormap_type: data[offset++],
  73850. image_type: data[offset++],
  73851. colormap_index: data[offset++] | data[offset++] << 8,
  73852. colormap_length: data[offset++] | data[offset++] << 8,
  73853. colormap_size: data[offset++],
  73854. origin: [
  73855. data[offset++] | data[offset++] << 8,
  73856. data[offset++] | data[offset++] << 8
  73857. ],
  73858. width: data[offset++] | data[offset++] << 8,
  73859. height: data[offset++] | data[offset++] << 8,
  73860. pixel_size: data[offset++],
  73861. flags: data[offset++]
  73862. };
  73863. return header;
  73864. };
  73865. TGATools.UploadContent = function (gl, data) {
  73866. // Not enough data to contain header ?
  73867. if (data.length < 19) {
  73868. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  73869. return;
  73870. }
  73871. // Read Header
  73872. var offset = 18;
  73873. var header = TGATools.GetTGAHeader(data);
  73874. // Assume it's a valid Targa file.
  73875. if (header.id_length + offset > data.length) {
  73876. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  73877. return;
  73878. }
  73879. // Skip not needed data
  73880. offset += header.id_length;
  73881. var use_rle = false;
  73882. var use_pal = false;
  73883. var use_grey = false;
  73884. // Get some informations.
  73885. switch (header.image_type) {
  73886. case TGATools._TYPE_RLE_INDEXED:
  73887. use_rle = true;
  73888. case TGATools._TYPE_INDEXED:
  73889. use_pal = true;
  73890. break;
  73891. case TGATools._TYPE_RLE_RGB:
  73892. use_rle = true;
  73893. case TGATools._TYPE_RGB:
  73894. // use_rgb = true;
  73895. break;
  73896. case TGATools._TYPE_RLE_GREY:
  73897. use_rle = true;
  73898. case TGATools._TYPE_GREY:
  73899. use_grey = true;
  73900. break;
  73901. }
  73902. var pixel_data;
  73903. // var numAlphaBits = header.flags & 0xf;
  73904. var pixel_size = header.pixel_size >> 3;
  73905. var pixel_total = header.width * header.height * pixel_size;
  73906. // Read palettes
  73907. var palettes;
  73908. if (use_pal) {
  73909. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  73910. }
  73911. // Read LRE
  73912. if (use_rle) {
  73913. pixel_data = new Uint8Array(pixel_total);
  73914. var c, count, i;
  73915. var localOffset = 0;
  73916. var pixels = new Uint8Array(pixel_size);
  73917. while (offset < pixel_total && localOffset < pixel_total) {
  73918. c = data[offset++];
  73919. count = (c & 0x7f) + 1;
  73920. // RLE pixels
  73921. if (c & 0x80) {
  73922. // Bind pixel tmp array
  73923. for (i = 0; i < pixel_size; ++i) {
  73924. pixels[i] = data[offset++];
  73925. }
  73926. // Copy pixel array
  73927. for (i = 0; i < count; ++i) {
  73928. pixel_data.set(pixels, localOffset + i * pixel_size);
  73929. }
  73930. localOffset += pixel_size * count;
  73931. }
  73932. else {
  73933. count *= pixel_size;
  73934. for (i = 0; i < count; ++i) {
  73935. pixel_data[localOffset + i] = data[offset++];
  73936. }
  73937. localOffset += count;
  73938. }
  73939. }
  73940. }
  73941. else {
  73942. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  73943. }
  73944. // Load to texture
  73945. var x_start, y_start, x_step, y_step, y_end, x_end;
  73946. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  73947. default:
  73948. case TGATools._ORIGIN_UL:
  73949. x_start = 0;
  73950. x_step = 1;
  73951. x_end = header.width;
  73952. y_start = 0;
  73953. y_step = 1;
  73954. y_end = header.height;
  73955. break;
  73956. case TGATools._ORIGIN_BL:
  73957. x_start = 0;
  73958. x_step = 1;
  73959. x_end = header.width;
  73960. y_start = header.height - 1;
  73961. y_step = -1;
  73962. y_end = -1;
  73963. break;
  73964. case TGATools._ORIGIN_UR:
  73965. x_start = header.width - 1;
  73966. x_step = -1;
  73967. x_end = -1;
  73968. y_start = 0;
  73969. y_step = 1;
  73970. y_end = header.height;
  73971. break;
  73972. case TGATools._ORIGIN_BR:
  73973. x_start = header.width - 1;
  73974. x_step = -1;
  73975. x_end = -1;
  73976. y_start = header.height - 1;
  73977. y_step = -1;
  73978. y_end = -1;
  73979. break;
  73980. }
  73981. // Load the specify method
  73982. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  73983. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  73984. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  73985. };
  73986. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73987. var image = pixel_data, colormap = palettes;
  73988. var width = header.width, height = header.height;
  73989. var color, i = 0, x, y;
  73990. var imageData = new Uint8Array(width * height * 4);
  73991. for (y = y_start; y !== y_end; y += y_step) {
  73992. for (x = x_start; x !== x_end; x += x_step, i++) {
  73993. color = image[i];
  73994. imageData[(x + width * y) * 4 + 3] = 255;
  73995. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  73996. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  73997. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  73998. }
  73999. }
  74000. return imageData;
  74001. };
  74002. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74003. var image = pixel_data;
  74004. var width = header.width, height = header.height;
  74005. var color, i = 0, x, y;
  74006. var imageData = new Uint8Array(width * height * 4);
  74007. for (y = y_start; y !== y_end; y += y_step) {
  74008. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  74009. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  74010. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  74011. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  74012. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  74013. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  74014. }
  74015. }
  74016. return imageData;
  74017. };
  74018. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74019. var image = pixel_data;
  74020. var width = header.width, height = header.height;
  74021. var i = 0, x, y;
  74022. var imageData = new Uint8Array(width * height * 4);
  74023. for (y = y_start; y !== y_end; y += y_step) {
  74024. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  74025. imageData[(x + width * y) * 4 + 3] = 255;
  74026. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  74027. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  74028. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  74029. }
  74030. }
  74031. return imageData;
  74032. };
  74033. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74034. var image = pixel_data;
  74035. var width = header.width, height = header.height;
  74036. var i = 0, x, y;
  74037. var imageData = new Uint8Array(width * height * 4);
  74038. for (y = y_start; y !== y_end; y += y_step) {
  74039. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  74040. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  74041. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  74042. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  74043. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  74044. }
  74045. }
  74046. return imageData;
  74047. };
  74048. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74049. var image = pixel_data;
  74050. var width = header.width, height = header.height;
  74051. var color, i = 0, x, y;
  74052. var imageData = new Uint8Array(width * height * 4);
  74053. for (y = y_start; y !== y_end; y += y_step) {
  74054. for (x = x_start; x !== x_end; x += x_step, i++) {
  74055. color = image[i];
  74056. imageData[(x + width * y) * 4 + 0] = color;
  74057. imageData[(x + width * y) * 4 + 1] = color;
  74058. imageData[(x + width * y) * 4 + 2] = color;
  74059. imageData[(x + width * y) * 4 + 3] = 255;
  74060. }
  74061. }
  74062. return imageData;
  74063. };
  74064. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  74065. var image = pixel_data;
  74066. var width = header.width, height = header.height;
  74067. var i = 0, x, y;
  74068. var imageData = new Uint8Array(width * height * 4);
  74069. for (y = y_start; y !== y_end; y += y_step) {
  74070. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  74071. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  74072. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  74073. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  74074. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  74075. }
  74076. }
  74077. return imageData;
  74078. };
  74079. //private static _TYPE_NO_DATA = 0;
  74080. TGATools._TYPE_INDEXED = 1;
  74081. TGATools._TYPE_RGB = 2;
  74082. TGATools._TYPE_GREY = 3;
  74083. TGATools._TYPE_RLE_INDEXED = 9;
  74084. TGATools._TYPE_RLE_RGB = 10;
  74085. TGATools._TYPE_RLE_GREY = 11;
  74086. TGATools._ORIGIN_MASK = 0x30;
  74087. TGATools._ORIGIN_SHIFT = 0x04;
  74088. TGATools._ORIGIN_BL = 0x00;
  74089. TGATools._ORIGIN_BR = 0x01;
  74090. TGATools._ORIGIN_UL = 0x02;
  74091. TGATools._ORIGIN_UR = 0x03;
  74092. return TGATools;
  74093. }());
  74094. BABYLON.TGATools = TGATools;
  74095. })(BABYLON || (BABYLON = {}));
  74096. //# sourceMappingURL=babylon.tga.js.map
  74097. var BABYLON;
  74098. (function (BABYLON) {
  74099. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  74100. // All values and structures referenced from:
  74101. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  74102. var DDS_MAGIC = 0x20534444;
  74103. var
  74104. //DDSD_CAPS = 0x1,
  74105. //DDSD_HEIGHT = 0x2,
  74106. //DDSD_WIDTH = 0x4,
  74107. //DDSD_PITCH = 0x8,
  74108. //DDSD_PIXELFORMAT = 0x1000,
  74109. DDSD_MIPMAPCOUNT = 0x20000;
  74110. //DDSD_LINEARSIZE = 0x80000,
  74111. //DDSD_DEPTH = 0x800000;
  74112. // var DDSCAPS_COMPLEX = 0x8,
  74113. // DDSCAPS_MIPMAP = 0x400000,
  74114. // DDSCAPS_TEXTURE = 0x1000;
  74115. var DDSCAPS2_CUBEMAP = 0x200;
  74116. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  74117. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  74118. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  74119. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  74120. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  74121. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  74122. // DDSCAPS2_VOLUME = 0x200000;
  74123. var
  74124. //DDPF_ALPHAPIXELS = 0x1,
  74125. //DDPF_ALPHA = 0x2,
  74126. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  74127. //DDPF_YUV = 0x200,
  74128. DDPF_LUMINANCE = 0x20000;
  74129. function FourCCToInt32(value) {
  74130. return value.charCodeAt(0) +
  74131. (value.charCodeAt(1) << 8) +
  74132. (value.charCodeAt(2) << 16) +
  74133. (value.charCodeAt(3) << 24);
  74134. }
  74135. function Int32ToFourCC(value) {
  74136. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  74137. }
  74138. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  74139. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  74140. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  74141. var FOURCC_DX10 = FourCCToInt32("DX10");
  74142. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  74143. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  74144. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  74145. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  74146. var headerLengthInt = 31; // The header length in 32 bit ints
  74147. // Offsets into the header array
  74148. var off_magic = 0;
  74149. var off_size = 1;
  74150. var off_flags = 2;
  74151. var off_height = 3;
  74152. var off_width = 4;
  74153. var off_mipmapCount = 7;
  74154. var off_pfFlags = 20;
  74155. var off_pfFourCC = 21;
  74156. var off_RGBbpp = 22;
  74157. var off_RMask = 23;
  74158. var off_GMask = 24;
  74159. var off_BMask = 25;
  74160. var off_AMask = 26;
  74161. // var off_caps1 = 27;
  74162. var off_caps2 = 28;
  74163. // var off_caps3 = 29;
  74164. // var off_caps4 = 30;
  74165. var off_dxgiFormat = 32;
  74166. ;
  74167. var DDSTools = /** @class */ (function () {
  74168. function DDSTools() {
  74169. }
  74170. DDSTools.GetDDSInfo = function (arrayBuffer) {
  74171. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  74172. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  74173. var mipmapCount = 1;
  74174. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  74175. mipmapCount = Math.max(1, header[off_mipmapCount]);
  74176. }
  74177. var fourCC = header[off_pfFourCC];
  74178. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  74179. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74180. switch (fourCC) {
  74181. case FOURCC_D3DFMT_R16G16B16A16F:
  74182. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74183. break;
  74184. case FOURCC_D3DFMT_R32G32B32A32F:
  74185. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74186. break;
  74187. case FOURCC_DX10:
  74188. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  74189. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74190. break;
  74191. }
  74192. }
  74193. return {
  74194. width: header[off_width],
  74195. height: header[off_height],
  74196. mipmapCount: mipmapCount,
  74197. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  74198. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  74199. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  74200. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  74201. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  74202. dxgiFormat: dxgiFormat,
  74203. textureType: textureType
  74204. };
  74205. };
  74206. DDSTools._ToHalfFloat = function (value) {
  74207. if (!DDSTools._FloatView) {
  74208. DDSTools._FloatView = new Float32Array(1);
  74209. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  74210. }
  74211. DDSTools._FloatView[0] = value;
  74212. var x = DDSTools._Int32View[0];
  74213. var bits = (x >> 16) & 0x8000; /* Get the sign */
  74214. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  74215. var e = (x >> 23) & 0xff; /* Using int is faster here */
  74216. /* If zero, or denormal, or exponent underflows too much for a denormal
  74217. * half, return signed zero. */
  74218. if (e < 103) {
  74219. return bits;
  74220. }
  74221. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  74222. if (e > 142) {
  74223. bits |= 0x7c00;
  74224. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  74225. * not Inf, so make sure we set one mantissa bit too. */
  74226. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  74227. return bits;
  74228. }
  74229. /* If exponent underflows but not too much, return a denormal */
  74230. if (e < 113) {
  74231. m |= 0x0800;
  74232. /* Extra rounding may overflow and set mantissa to 0 and exponent
  74233. * to 1, which is OK. */
  74234. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  74235. return bits;
  74236. }
  74237. bits |= ((e - 112) << 10) | (m >> 1);
  74238. bits += m & 1;
  74239. return bits;
  74240. };
  74241. DDSTools._FromHalfFloat = function (value) {
  74242. var s = (value & 0x8000) >> 15;
  74243. var e = (value & 0x7C00) >> 10;
  74244. var f = value & 0x03FF;
  74245. if (e === 0) {
  74246. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  74247. }
  74248. else if (e == 0x1F) {
  74249. return f ? NaN : ((s ? -1 : 1) * Infinity);
  74250. }
  74251. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  74252. };
  74253. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74254. var destArray = new Float32Array(dataLength);
  74255. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  74256. var index = 0;
  74257. for (var y = 0; y < height; y++) {
  74258. for (var x = 0; x < width; x++) {
  74259. var srcPos = (x + y * width) * 4;
  74260. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  74261. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  74262. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  74263. if (DDSTools.StoreLODInAlphaChannel) {
  74264. destArray[index + 3] = lod;
  74265. }
  74266. else {
  74267. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  74268. }
  74269. index += 4;
  74270. }
  74271. }
  74272. return destArray;
  74273. };
  74274. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74275. if (DDSTools.StoreLODInAlphaChannel) {
  74276. var destArray = new Uint16Array(dataLength);
  74277. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  74278. var index = 0;
  74279. for (var y = 0; y < height; y++) {
  74280. for (var x = 0; x < width; x++) {
  74281. var srcPos = (x + y * width) * 4;
  74282. destArray[index] = srcData[srcPos];
  74283. destArray[index + 1] = srcData[srcPos + 1];
  74284. destArray[index + 2] = srcData[srcPos + 2];
  74285. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  74286. index += 4;
  74287. }
  74288. }
  74289. return destArray;
  74290. }
  74291. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  74292. };
  74293. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74294. if (DDSTools.StoreLODInAlphaChannel) {
  74295. var destArray = new Float32Array(dataLength);
  74296. var srcData = new Float32Array(arrayBuffer, dataOffset);
  74297. var index = 0;
  74298. for (var y = 0; y < height; y++) {
  74299. for (var x = 0; x < width; x++) {
  74300. var srcPos = (x + y * width) * 4;
  74301. destArray[index] = srcData[srcPos];
  74302. destArray[index + 1] = srcData[srcPos + 1];
  74303. destArray[index + 2] = srcData[srcPos + 2];
  74304. destArray[index + 3] = lod;
  74305. index += 4;
  74306. }
  74307. }
  74308. return destArray;
  74309. }
  74310. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  74311. };
  74312. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74313. var destArray = new Uint8Array(dataLength);
  74314. var srcData = new Float32Array(arrayBuffer, dataOffset);
  74315. var index = 0;
  74316. for (var y = 0; y < height; y++) {
  74317. for (var x = 0; x < width; x++) {
  74318. var srcPos = (x + y * width) * 4;
  74319. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  74320. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  74321. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  74322. if (DDSTools.StoreLODInAlphaChannel) {
  74323. destArray[index + 3] = lod;
  74324. }
  74325. else {
  74326. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  74327. }
  74328. index += 4;
  74329. }
  74330. }
  74331. return destArray;
  74332. };
  74333. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  74334. var destArray = new Uint8Array(dataLength);
  74335. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  74336. var index = 0;
  74337. for (var y = 0; y < height; y++) {
  74338. for (var x = 0; x < width; x++) {
  74339. var srcPos = (x + y * width) * 4;
  74340. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  74341. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  74342. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  74343. if (DDSTools.StoreLODInAlphaChannel) {
  74344. destArray[index + 3] = lod;
  74345. }
  74346. else {
  74347. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  74348. }
  74349. index += 4;
  74350. }
  74351. }
  74352. return destArray;
  74353. };
  74354. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  74355. var byteArray = new Uint8Array(dataLength);
  74356. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  74357. var index = 0;
  74358. for (var y = 0; y < height; y++) {
  74359. for (var x = 0; x < width; x++) {
  74360. var srcPos = (x + y * width) * 4;
  74361. byteArray[index] = srcData[srcPos + rOffset];
  74362. byteArray[index + 1] = srcData[srcPos + gOffset];
  74363. byteArray[index + 2] = srcData[srcPos + bOffset];
  74364. byteArray[index + 3] = srcData[srcPos + aOffset];
  74365. index += 4;
  74366. }
  74367. }
  74368. return byteArray;
  74369. };
  74370. DDSTools._ExtractLongWordOrder = function (value) {
  74371. if (value === 0 || value === 255 || value === -16777216) {
  74372. return 0;
  74373. }
  74374. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  74375. };
  74376. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  74377. var byteArray = new Uint8Array(dataLength);
  74378. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  74379. var index = 0;
  74380. for (var y = 0; y < height; y++) {
  74381. for (var x = 0; x < width; x++) {
  74382. var srcPos = (x + y * width) * 3;
  74383. byteArray[index] = srcData[srcPos + rOffset];
  74384. byteArray[index + 1] = srcData[srcPos + gOffset];
  74385. byteArray[index + 2] = srcData[srcPos + bOffset];
  74386. index += 3;
  74387. }
  74388. }
  74389. return byteArray;
  74390. };
  74391. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  74392. var byteArray = new Uint8Array(dataLength);
  74393. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  74394. var index = 0;
  74395. for (var y = 0; y < height; y++) {
  74396. for (var x = 0; x < width; x++) {
  74397. var srcPos = (x + y * width);
  74398. byteArray[index] = srcData[srcPos];
  74399. index++;
  74400. }
  74401. }
  74402. return byteArray;
  74403. };
  74404. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  74405. if (lodIndex === void 0) { lodIndex = -1; }
  74406. var ext = engine.getCaps().s3tc;
  74407. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  74408. var fourCC, width, height, dataLength = 0, dataOffset;
  74409. var byteArray, mipmapCount, mip;
  74410. var internalFormat = 0;
  74411. var format = 0;
  74412. var blockBytes = 1;
  74413. if (header[off_magic] !== DDS_MAGIC) {
  74414. BABYLON.Tools.Error("Invalid magic number in DDS header");
  74415. return;
  74416. }
  74417. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  74418. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  74419. return;
  74420. }
  74421. if (info.isCompressed && !ext) {
  74422. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  74423. return;
  74424. }
  74425. var bpp = header[off_RGBbpp];
  74426. dataOffset = header[off_size] + 4;
  74427. var computeFormats = false;
  74428. if (info.isFourCC) {
  74429. fourCC = header[off_pfFourCC];
  74430. switch (fourCC) {
  74431. case FOURCC_DXT1:
  74432. blockBytes = 8;
  74433. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  74434. break;
  74435. case FOURCC_DXT3:
  74436. blockBytes = 16;
  74437. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  74438. break;
  74439. case FOURCC_DXT5:
  74440. blockBytes = 16;
  74441. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  74442. break;
  74443. case FOURCC_D3DFMT_R16G16B16A16F:
  74444. computeFormats = true;
  74445. break;
  74446. case FOURCC_D3DFMT_R32G32B32A32F:
  74447. computeFormats = true;
  74448. break;
  74449. case FOURCC_DX10:
  74450. // There is an additionnal header so dataOffset need to be changed
  74451. dataOffset += 5 * 4; // 5 uints
  74452. var supported = false;
  74453. switch (info.dxgiFormat) {
  74454. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  74455. computeFormats = true;
  74456. supported = true;
  74457. break;
  74458. case DXGI_FORMAT_B8G8R8X8_UNORM:
  74459. info.isRGB = true;
  74460. info.isFourCC = false;
  74461. bpp = 32;
  74462. supported = true;
  74463. break;
  74464. }
  74465. if (supported) {
  74466. break;
  74467. }
  74468. default:
  74469. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  74470. return;
  74471. }
  74472. }
  74473. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  74474. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  74475. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  74476. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  74477. if (computeFormats) {
  74478. format = engine._getWebGLTextureType(info.textureType);
  74479. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  74480. }
  74481. mipmapCount = 1;
  74482. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  74483. mipmapCount = Math.max(1, header[off_mipmapCount]);
  74484. }
  74485. for (var face = 0; face < faces; face++) {
  74486. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  74487. width = header[off_width];
  74488. height = header[off_height];
  74489. for (mip = 0; mip < mipmapCount; ++mip) {
  74490. if (lodIndex === -1 || lodIndex === mip) {
  74491. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  74492. var i = (lodIndex === -1) ? mip : 0;
  74493. if (!info.isCompressed && info.isFourCC) {
  74494. dataLength = width * height * 4;
  74495. var floatArray = null;
  74496. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  74497. if (bpp === 128) {
  74498. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74499. }
  74500. else if (bpp === 64) {
  74501. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74502. }
  74503. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74504. format = engine._getWebGLTextureType(info.textureType);
  74505. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  74506. }
  74507. else {
  74508. if (bpp === 128) {
  74509. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74510. }
  74511. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  74512. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74513. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74514. format = engine._getWebGLTextureType(info.textureType);
  74515. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  74516. }
  74517. else {
  74518. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  74519. }
  74520. }
  74521. if (floatArray) {
  74522. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  74523. }
  74524. }
  74525. else if (info.isRGB) {
  74526. if (bpp === 24) {
  74527. dataLength = width * height * 3;
  74528. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  74529. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  74530. }
  74531. else {
  74532. dataLength = width * height * 4;
  74533. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  74534. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  74535. }
  74536. }
  74537. else if (info.isLuminance) {
  74538. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  74539. var unpaddedRowSize = width;
  74540. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  74541. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  74542. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  74543. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  74544. }
  74545. else {
  74546. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  74547. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  74548. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  74549. }
  74550. }
  74551. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  74552. width *= 0.5;
  74553. height *= 0.5;
  74554. width = Math.max(1.0, width);
  74555. height = Math.max(1.0, height);
  74556. }
  74557. if (currentFace !== undefined) {
  74558. // Loading a single face
  74559. break;
  74560. }
  74561. }
  74562. };
  74563. DDSTools.StoreLODInAlphaChannel = false;
  74564. return DDSTools;
  74565. }());
  74566. BABYLON.DDSTools = DDSTools;
  74567. })(BABYLON || (BABYLON = {}));
  74568. //# sourceMappingURL=babylon.dds.js.map
  74569. var BABYLON;
  74570. (function (BABYLON) {
  74571. /**
  74572. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  74573. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  74574. */
  74575. var KhronosTextureContainer = /** @class */ (function () {
  74576. /**
  74577. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  74578. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  74579. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  74580. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  74581. */
  74582. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  74583. this.arrayBuffer = arrayBuffer;
  74584. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  74585. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  74586. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  74587. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  74588. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  74589. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  74590. BABYLON.Tools.Error("texture missing KTX identifier");
  74591. return;
  74592. }
  74593. // load the reset of the header in native 32 bit int
  74594. var header = new Int32Array(this.arrayBuffer, 12, 13);
  74595. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  74596. var oppositeEndianess = header[0] === 0x01020304;
  74597. // read all the header elements in order they exist in the file, without modification (sans endainness)
  74598. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  74599. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  74600. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  74601. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  74602. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  74603. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  74604. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  74605. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  74606. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  74607. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  74608. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  74609. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  74610. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  74611. if (this.glType !== 0) {
  74612. BABYLON.Tools.Error("only compressed formats currently supported");
  74613. return;
  74614. }
  74615. else {
  74616. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  74617. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  74618. }
  74619. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  74620. BABYLON.Tools.Error("only 2D textures currently supported");
  74621. return;
  74622. }
  74623. if (this.numberOfArrayElements !== 0) {
  74624. BABYLON.Tools.Error("texture arrays not currently supported");
  74625. return;
  74626. }
  74627. if (this.numberOfFaces !== facesExpected) {
  74628. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  74629. return;
  74630. }
  74631. // we now have a completely validated file, so could use existence of loadType as success
  74632. // would need to make this more elaborate & adjust checks above to support more than one load type
  74633. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  74634. }
  74635. // not as fast hardware based, but will probably never need to use
  74636. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  74637. return ((val & 0xFF) << 24)
  74638. | ((val & 0xFF00) << 8)
  74639. | ((val >> 8) & 0xFF00)
  74640. | ((val >> 24) & 0xFF);
  74641. };
  74642. /**
  74643. * It is assumed that the texture has already been created & is currently bound
  74644. */
  74645. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  74646. switch (this.loadType) {
  74647. case KhronosTextureContainer.COMPRESSED_2D:
  74648. this._upload2DCompressedLevels(gl, loadMipmaps);
  74649. break;
  74650. case KhronosTextureContainer.TEX_2D:
  74651. case KhronosTextureContainer.COMPRESSED_3D:
  74652. case KhronosTextureContainer.TEX_3D:
  74653. }
  74654. };
  74655. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  74656. // initialize width & height for level 1
  74657. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  74658. var width = this.pixelWidth;
  74659. var height = this.pixelHeight;
  74660. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  74661. for (var level = 0; level < mipmapCount; level++) {
  74662. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  74663. for (var face = 0; face < this.numberOfFaces; face++) {
  74664. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  74665. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  74666. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  74667. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  74668. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  74669. }
  74670. width = Math.max(1.0, width * 0.5);
  74671. height = Math.max(1.0, height * 0.5);
  74672. }
  74673. };
  74674. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  74675. // load types
  74676. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  74677. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  74678. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  74679. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  74680. return KhronosTextureContainer;
  74681. }());
  74682. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  74683. })(BABYLON || (BABYLON = {}));
  74684. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  74685. var BABYLON;
  74686. (function (BABYLON) {
  74687. var Debug = /** @class */ (function () {
  74688. function Debug() {
  74689. }
  74690. Debug.AxesViewer = /** @class */ (function () {
  74691. function AxesViewer(scene, scaleLines) {
  74692. if (scaleLines === void 0) { scaleLines = 1; }
  74693. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74694. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74695. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74696. this.scaleLines = 1;
  74697. this.scaleLines = scaleLines;
  74698. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  74699. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  74700. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  74701. this._xmesh.renderingGroupId = 2;
  74702. this._ymesh.renderingGroupId = 2;
  74703. this._zmesh.renderingGroupId = 2;
  74704. this._xmesh.material.checkReadyOnlyOnce = true;
  74705. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  74706. this._ymesh.material.checkReadyOnlyOnce = true;
  74707. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  74708. this._zmesh.material.checkReadyOnlyOnce = true;
  74709. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  74710. this.scene = scene;
  74711. }
  74712. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  74713. var scaleLines = this.scaleLines;
  74714. if (this._xmesh) {
  74715. this._xmesh.position.copyFrom(position);
  74716. }
  74717. if (this._ymesh) {
  74718. this._ymesh.position.copyFrom(position);
  74719. }
  74720. if (this._zmesh) {
  74721. this._zmesh.position.copyFrom(position);
  74722. }
  74723. var point2 = this._xline[1];
  74724. point2.x = xaxis.x * scaleLines;
  74725. point2.y = xaxis.y * scaleLines;
  74726. point2.z = xaxis.z * scaleLines;
  74727. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  74728. point2 = this._yline[1];
  74729. point2.x = yaxis.x * scaleLines;
  74730. point2.y = yaxis.y * scaleLines;
  74731. point2.z = yaxis.z * scaleLines;
  74732. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  74733. point2 = this._zline[1];
  74734. point2.x = zaxis.x * scaleLines;
  74735. point2.y = zaxis.y * scaleLines;
  74736. point2.z = zaxis.z * scaleLines;
  74737. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  74738. };
  74739. AxesViewer.prototype.dispose = function () {
  74740. if (this._xmesh) {
  74741. this._xmesh.dispose();
  74742. }
  74743. if (this._ymesh) {
  74744. this._ymesh.dispose();
  74745. }
  74746. if (this._zmesh) {
  74747. this._zmesh.dispose();
  74748. }
  74749. this._xmesh = null;
  74750. this._ymesh = null;
  74751. this._zmesh = null;
  74752. this.scene = null;
  74753. };
  74754. return AxesViewer;
  74755. }());
  74756. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  74757. __extends(BoneAxesViewer, _super);
  74758. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  74759. if (scaleLines === void 0) { scaleLines = 1; }
  74760. var _this = _super.call(this, scene, scaleLines) || this;
  74761. _this.pos = BABYLON.Vector3.Zero();
  74762. _this.xaxis = BABYLON.Vector3.Zero();
  74763. _this.yaxis = BABYLON.Vector3.Zero();
  74764. _this.zaxis = BABYLON.Vector3.Zero();
  74765. _this.mesh = mesh;
  74766. _this.bone = bone;
  74767. return _this;
  74768. }
  74769. BoneAxesViewer.prototype.update = function () {
  74770. if (!this.mesh || !this.bone) {
  74771. return;
  74772. }
  74773. var bone = this.bone;
  74774. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  74775. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  74776. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  74777. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  74778. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  74779. };
  74780. BoneAxesViewer.prototype.dispose = function () {
  74781. if (this.mesh) {
  74782. this.mesh = null;
  74783. this.bone = null;
  74784. _super.prototype.dispose.call(this);
  74785. }
  74786. };
  74787. return BoneAxesViewer;
  74788. }(Debug.AxesViewer));
  74789. Debug.PhysicsViewer = /** @class */ (function () {
  74790. function PhysicsViewer(scene) {
  74791. this._impostors = [];
  74792. this._meshes = [];
  74793. this._numMeshes = 0;
  74794. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74795. var physicEngine = this._scene.getPhysicsEngine();
  74796. if (physicEngine) {
  74797. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  74798. }
  74799. }
  74800. PhysicsViewer.prototype._updateDebugMeshes = function () {
  74801. var plugin = this._physicsEnginePlugin;
  74802. for (var i = 0; i < this._numMeshes; i++) {
  74803. var impostor = this._impostors[i];
  74804. if (!impostor) {
  74805. continue;
  74806. }
  74807. if (impostor.isDisposed) {
  74808. this.hideImpostor(this._impostors[i--]);
  74809. }
  74810. else {
  74811. var mesh = this._meshes[i];
  74812. if (mesh && plugin) {
  74813. plugin.syncMeshWithImpostor(mesh, impostor);
  74814. }
  74815. }
  74816. }
  74817. };
  74818. PhysicsViewer.prototype.showImpostor = function (impostor) {
  74819. if (!this._scene) {
  74820. return;
  74821. }
  74822. for (var i = 0; i < this._numMeshes; i++) {
  74823. if (this._impostors[i] == impostor) {
  74824. return;
  74825. }
  74826. }
  74827. var debugMesh = this._getDebugMesh(impostor, this._scene);
  74828. if (debugMesh) {
  74829. this._impostors[this._numMeshes] = impostor;
  74830. this._meshes[this._numMeshes] = debugMesh;
  74831. if (this._numMeshes === 0) {
  74832. this._renderFunction = this._updateDebugMeshes.bind(this);
  74833. this._scene.registerBeforeRender(this._renderFunction);
  74834. }
  74835. this._numMeshes++;
  74836. }
  74837. };
  74838. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  74839. if (!impostor || !this._scene) {
  74840. return;
  74841. }
  74842. var removed = false;
  74843. for (var i = 0; i < this._numMeshes; i++) {
  74844. if (this._impostors[i] == impostor) {
  74845. var mesh = this._meshes[i];
  74846. if (!mesh) {
  74847. continue;
  74848. }
  74849. this._scene.removeMesh(mesh);
  74850. mesh.dispose();
  74851. this._numMeshes--;
  74852. if (this._numMeshes > 0) {
  74853. this._meshes[i] = this._meshes[this._numMeshes];
  74854. this._impostors[i] = this._impostors[this._numMeshes];
  74855. this._meshes[this._numMeshes] = null;
  74856. this._impostors[this._numMeshes] = null;
  74857. }
  74858. else {
  74859. this._meshes[0] = null;
  74860. this._impostors[0] = null;
  74861. }
  74862. removed = true;
  74863. break;
  74864. }
  74865. }
  74866. if (removed && this._numMeshes === 0) {
  74867. this._scene.unregisterBeforeRender(this._renderFunction);
  74868. }
  74869. };
  74870. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  74871. if (!this._debugMaterial) {
  74872. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  74873. this._debugMaterial.wireframe = true;
  74874. }
  74875. return this._debugMaterial;
  74876. };
  74877. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  74878. if (!this._debugBoxMesh) {
  74879. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  74880. this._debugBoxMesh.renderingGroupId = 1;
  74881. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74882. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  74883. scene.removeMesh(this._debugBoxMesh);
  74884. }
  74885. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  74886. };
  74887. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  74888. if (!this._debugSphereMesh) {
  74889. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  74890. this._debugSphereMesh.renderingGroupId = 1;
  74891. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74892. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  74893. scene.removeMesh(this._debugSphereMesh);
  74894. }
  74895. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  74896. };
  74897. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  74898. var mesh = null;
  74899. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  74900. mesh = this._getDebugBoxMesh(scene);
  74901. impostor.getBoxSizeToRef(mesh.scaling);
  74902. }
  74903. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  74904. mesh = this._getDebugSphereMesh(scene);
  74905. var radius = impostor.getRadius();
  74906. mesh.scaling.x = radius * 2;
  74907. mesh.scaling.y = radius * 2;
  74908. mesh.scaling.z = radius * 2;
  74909. }
  74910. return mesh;
  74911. };
  74912. PhysicsViewer.prototype.dispose = function () {
  74913. for (var i = 0; i < this._numMeshes; i++) {
  74914. this.hideImpostor(this._impostors[i]);
  74915. }
  74916. if (this._debugBoxMesh) {
  74917. this._debugBoxMesh.dispose();
  74918. }
  74919. if (this._debugSphereMesh) {
  74920. this._debugSphereMesh.dispose();
  74921. }
  74922. if (this._debugMaterial) {
  74923. this._debugMaterial.dispose();
  74924. }
  74925. this._impostors.length = 0;
  74926. this._scene = null;
  74927. this._physicsEnginePlugin = null;
  74928. };
  74929. return PhysicsViewer;
  74930. }());
  74931. Debug.SkeletonViewer = /** @class */ (function () {
  74932. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  74933. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  74934. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  74935. this.skeleton = skeleton;
  74936. this.mesh = mesh;
  74937. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  74938. this.renderingGroupId = renderingGroupId;
  74939. this.color = BABYLON.Color3.White();
  74940. this._debugLines = new Array();
  74941. this._isEnabled = false;
  74942. this._scene = scene;
  74943. this.update();
  74944. this._renderFunction = this.update.bind(this);
  74945. }
  74946. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  74947. get: function () {
  74948. return this._isEnabled;
  74949. },
  74950. set: function (value) {
  74951. if (this._isEnabled === value) {
  74952. return;
  74953. }
  74954. this._isEnabled = value;
  74955. if (value) {
  74956. this._scene.registerBeforeRender(this._renderFunction);
  74957. }
  74958. else {
  74959. this._scene.unregisterBeforeRender(this._renderFunction);
  74960. }
  74961. },
  74962. enumerable: true,
  74963. configurable: true
  74964. });
  74965. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  74966. if (x === void 0) { x = 0; }
  74967. if (y === void 0) { y = 0; }
  74968. if (z === void 0) { z = 0; }
  74969. var tmat = BABYLON.Tmp.Matrix[0];
  74970. var parentBone = bone.getParent();
  74971. tmat.copyFrom(bone.getLocalMatrix());
  74972. if (x !== 0 || y !== 0 || z !== 0) {
  74973. var tmat2 = BABYLON.Tmp.Matrix[1];
  74974. BABYLON.Matrix.IdentityToRef(tmat2);
  74975. tmat2.m[12] = x;
  74976. tmat2.m[13] = y;
  74977. tmat2.m[14] = z;
  74978. tmat2.multiplyToRef(tmat, tmat);
  74979. }
  74980. if (parentBone) {
  74981. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  74982. }
  74983. tmat.multiplyToRef(meshMat, tmat);
  74984. position.x = tmat.m[12];
  74985. position.y = tmat.m[13];
  74986. position.z = tmat.m[14];
  74987. };
  74988. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  74989. var len = bones.length;
  74990. var meshPos = this.mesh.position;
  74991. for (var i = 0; i < len; i++) {
  74992. var bone = bones[i];
  74993. var points = this._debugLines[i];
  74994. if (!points) {
  74995. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74996. this._debugLines[i] = points;
  74997. }
  74998. this._getBonePosition(points[0], bone, meshMat);
  74999. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  75000. points[0].subtractInPlace(meshPos);
  75001. points[1].subtractInPlace(meshPos);
  75002. }
  75003. };
  75004. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  75005. var len = bones.length;
  75006. var boneNum = 0;
  75007. var meshPos = this.mesh.position;
  75008. for (var i = len - 1; i >= 0; i--) {
  75009. var childBone = bones[i];
  75010. var parentBone = childBone.getParent();
  75011. if (!parentBone) {
  75012. continue;
  75013. }
  75014. var points = this._debugLines[boneNum];
  75015. if (!points) {
  75016. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75017. this._debugLines[boneNum] = points;
  75018. }
  75019. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  75020. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  75021. points[0].subtractInPlace(meshPos);
  75022. points[1].subtractInPlace(meshPos);
  75023. boneNum++;
  75024. }
  75025. };
  75026. SkeletonViewer.prototype.update = function () {
  75027. if (this.autoUpdateBonesMatrices) {
  75028. this.skeleton.computeAbsoluteTransforms();
  75029. }
  75030. if (this.skeleton.bones[0].length === undefined) {
  75031. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  75032. }
  75033. else {
  75034. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  75035. }
  75036. if (!this._debugMesh) {
  75037. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  75038. this._debugMesh.renderingGroupId = this.renderingGroupId;
  75039. }
  75040. else {
  75041. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  75042. }
  75043. this._debugMesh.position.copyFrom(this.mesh.position);
  75044. this._debugMesh.color = this.color;
  75045. };
  75046. SkeletonViewer.prototype.dispose = function () {
  75047. if (this._debugMesh) {
  75048. this.isEnabled = false;
  75049. this._debugMesh.dispose();
  75050. this._debugMesh = null;
  75051. }
  75052. };
  75053. return SkeletonViewer;
  75054. }());
  75055. return Debug;
  75056. }());
  75057. BABYLON.Debug = Debug;
  75058. })(BABYLON || (BABYLON = {}));
  75059. //# sourceMappingURL=babylon.debugModules.js.map
  75060. var BABYLON;
  75061. (function (BABYLON) {
  75062. var RayHelper = /** @class */ (function () {
  75063. function RayHelper(ray) {
  75064. this.ray = ray;
  75065. }
  75066. RayHelper.CreateAndShow = function (ray, scene, color) {
  75067. var helper = new RayHelper(ray);
  75068. helper.show(scene, color);
  75069. return helper;
  75070. };
  75071. RayHelper.prototype.show = function (scene, color) {
  75072. if (!this._renderFunction && this.ray) {
  75073. var ray = this.ray;
  75074. this._renderFunction = this._render.bind(this);
  75075. this._scene = scene;
  75076. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  75077. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  75078. if (this._renderFunction) {
  75079. this._scene.registerBeforeRender(this._renderFunction);
  75080. }
  75081. }
  75082. if (color && this._renderLine) {
  75083. this._renderLine.color.copyFrom(color);
  75084. }
  75085. };
  75086. RayHelper.prototype.hide = function () {
  75087. if (this._renderFunction && this._scene) {
  75088. this._scene.unregisterBeforeRender(this._renderFunction);
  75089. this._scene = null;
  75090. this._renderFunction = null;
  75091. if (this._renderLine) {
  75092. this._renderLine.dispose();
  75093. this._renderLine = null;
  75094. }
  75095. this._renderPoints = [];
  75096. }
  75097. };
  75098. RayHelper.prototype._render = function () {
  75099. var ray = this.ray;
  75100. if (!ray) {
  75101. return;
  75102. }
  75103. var point = this._renderPoints[1];
  75104. var len = Math.min(ray.length, 1000000);
  75105. point.copyFrom(ray.direction);
  75106. point.scaleInPlace(len);
  75107. point.addInPlace(ray.origin);
  75108. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  75109. };
  75110. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  75111. this._attachedToMesh = mesh;
  75112. var ray = this.ray;
  75113. if (!ray) {
  75114. return;
  75115. }
  75116. if (!ray.direction) {
  75117. ray.direction = BABYLON.Vector3.Zero();
  75118. }
  75119. if (!ray.origin) {
  75120. ray.origin = BABYLON.Vector3.Zero();
  75121. }
  75122. if (length) {
  75123. ray.length = length;
  75124. }
  75125. if (!meshSpaceOrigin) {
  75126. meshSpaceOrigin = BABYLON.Vector3.Zero();
  75127. }
  75128. if (!meshSpaceDirection) {
  75129. // -1 so that this will work with Mesh.lookAt
  75130. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  75131. }
  75132. if (!this._meshSpaceDirection) {
  75133. this._meshSpaceDirection = meshSpaceDirection.clone();
  75134. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  75135. }
  75136. else {
  75137. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  75138. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  75139. }
  75140. if (!this._updateToMeshFunction) {
  75141. this._updateToMeshFunction = this._updateToMesh.bind(this);
  75142. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  75143. }
  75144. this._updateToMesh();
  75145. };
  75146. RayHelper.prototype.detachFromMesh = function () {
  75147. if (this._attachedToMesh) {
  75148. if (this._updateToMeshFunction) {
  75149. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  75150. }
  75151. this._attachedToMesh = null;
  75152. this._updateToMeshFunction = null;
  75153. }
  75154. };
  75155. RayHelper.prototype._updateToMesh = function () {
  75156. var ray = this.ray;
  75157. if (!this._attachedToMesh || !ray) {
  75158. return;
  75159. }
  75160. if (this._attachedToMesh._isDisposed) {
  75161. this.detachFromMesh();
  75162. return;
  75163. }
  75164. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  75165. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  75166. };
  75167. RayHelper.prototype.dispose = function () {
  75168. this.hide();
  75169. this.detachFromMesh();
  75170. this.ray = null;
  75171. };
  75172. return RayHelper;
  75173. }());
  75174. BABYLON.RayHelper = RayHelper;
  75175. })(BABYLON || (BABYLON = {}));
  75176. //# sourceMappingURL=babylon.rayHelper.js.map
  75177. var BABYLON;
  75178. (function (BABYLON) {
  75179. // load the inspector using require, if not present in the global namespace.
  75180. var DebugLayer = /** @class */ (function () {
  75181. function DebugLayer(scene) {
  75182. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  75183. this._scene = scene;
  75184. // load inspector using require, if it doesn't exist on the global namespace.
  75185. }
  75186. /** Creates the inspector window. */
  75187. DebugLayer.prototype._createInspector = function (config) {
  75188. if (config === void 0) { config = {}; }
  75189. var popup = config.popup || false;
  75190. var initialTab = config.initialTab || 0;
  75191. var parentElement = config.parentElement || null;
  75192. if (!this._inspector) {
  75193. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  75194. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  75195. } // else nothing to do,; instance is already existing
  75196. };
  75197. DebugLayer.prototype.isVisible = function () {
  75198. if (!this._inspector) {
  75199. return false;
  75200. }
  75201. return true;
  75202. };
  75203. DebugLayer.prototype.hide = function () {
  75204. if (this._inspector) {
  75205. try {
  75206. this._inspector.dispose();
  75207. }
  75208. catch (e) {
  75209. // If the inspector has been removed directly from the inspector tool
  75210. }
  75211. this._inspector = null;
  75212. }
  75213. };
  75214. DebugLayer.prototype.show = function (config) {
  75215. if (config === void 0) { config = {}; }
  75216. if (typeof this.BJSINSPECTOR == 'undefined') {
  75217. // Load inspector and add it to the DOM
  75218. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  75219. }
  75220. else {
  75221. // Otherwise creates the inspector
  75222. this._createInspector(config);
  75223. }
  75224. };
  75225. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  75226. return DebugLayer;
  75227. }());
  75228. BABYLON.DebugLayer = DebugLayer;
  75229. })(BABYLON || (BABYLON = {}));
  75230. //# sourceMappingURL=babylon.debugLayer.js.map
  75231. var BABYLON;
  75232. (function (BABYLON) {
  75233. var BoundingBoxRenderer = /** @class */ (function () {
  75234. function BoundingBoxRenderer(scene) {
  75235. this.frontColor = new BABYLON.Color3(1, 1, 1);
  75236. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  75237. this.showBackLines = true;
  75238. this.renderList = new BABYLON.SmartArray(32);
  75239. this._vertexBuffers = {};
  75240. this._scene = scene;
  75241. }
  75242. BoundingBoxRenderer.prototype._prepareRessources = function () {
  75243. if (this._colorShader) {
  75244. return;
  75245. }
  75246. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  75247. attributes: [BABYLON.VertexBuffer.PositionKind],
  75248. uniforms: ["world", "viewProjection", "color"]
  75249. });
  75250. var engine = this._scene.getEngine();
  75251. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  75252. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  75253. this._createIndexBuffer();
  75254. };
  75255. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  75256. var engine = this._scene.getEngine();
  75257. 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]);
  75258. };
  75259. BoundingBoxRenderer.prototype._rebuild = function () {
  75260. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75261. if (vb) {
  75262. vb._rebuild();
  75263. }
  75264. this._createIndexBuffer();
  75265. };
  75266. BoundingBoxRenderer.prototype.reset = function () {
  75267. this.renderList.reset();
  75268. };
  75269. BoundingBoxRenderer.prototype.render = function () {
  75270. if (this.renderList.length === 0) {
  75271. return;
  75272. }
  75273. this._prepareRessources();
  75274. if (!this._colorShader.isReady()) {
  75275. return;
  75276. }
  75277. var engine = this._scene.getEngine();
  75278. engine.setDepthWrite(false);
  75279. this._colorShader._preBind();
  75280. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  75281. var boundingBox = this.renderList.data[boundingBoxIndex];
  75282. var min = boundingBox.minimum;
  75283. var max = boundingBox.maximum;
  75284. var diff = max.subtract(min);
  75285. var median = min.add(diff.scale(0.5));
  75286. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  75287. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  75288. .multiply(boundingBox.getWorldMatrix());
  75289. // VBOs
  75290. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  75291. if (this.showBackLines) {
  75292. // Back
  75293. engine.setDepthFunctionToGreaterOrEqual();
  75294. this._scene.resetCachedMaterial();
  75295. this._colorShader.setColor4("color", this.backColor.toColor4());
  75296. this._colorShader.bind(worldMatrix);
  75297. // Draw order
  75298. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  75299. }
  75300. // Front
  75301. engine.setDepthFunctionToLess();
  75302. this._scene.resetCachedMaterial();
  75303. this._colorShader.setColor4("color", this.frontColor.toColor4());
  75304. this._colorShader.bind(worldMatrix);
  75305. // Draw order
  75306. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  75307. }
  75308. this._colorShader.unbind();
  75309. engine.setDepthFunctionToLessOrEqual();
  75310. engine.setDepthWrite(true);
  75311. };
  75312. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  75313. this._prepareRessources();
  75314. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  75315. return;
  75316. }
  75317. var engine = this._scene.getEngine();
  75318. engine.setDepthWrite(false);
  75319. engine.setColorWrite(false);
  75320. this._colorShader._preBind();
  75321. var boundingBox = mesh._boundingInfo.boundingBox;
  75322. var min = boundingBox.minimum;
  75323. var max = boundingBox.maximum;
  75324. var diff = max.subtract(min);
  75325. var median = min.add(diff.scale(0.5));
  75326. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  75327. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  75328. .multiply(boundingBox.getWorldMatrix());
  75329. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  75330. engine.setDepthFunctionToLess();
  75331. this._scene.resetCachedMaterial();
  75332. this._colorShader.bind(worldMatrix);
  75333. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  75334. this._colorShader.unbind();
  75335. engine.setDepthFunctionToLessOrEqual();
  75336. engine.setDepthWrite(true);
  75337. engine.setColorWrite(true);
  75338. };
  75339. BoundingBoxRenderer.prototype.dispose = function () {
  75340. if (!this._colorShader) {
  75341. return;
  75342. }
  75343. this.renderList.dispose();
  75344. this._colorShader.dispose();
  75345. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75346. if (buffer) {
  75347. buffer.dispose();
  75348. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75349. }
  75350. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75351. };
  75352. return BoundingBoxRenderer;
  75353. }());
  75354. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  75355. })(BABYLON || (BABYLON = {}));
  75356. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  75357. var BABYLON;
  75358. (function (BABYLON) {
  75359. var MorphTarget = /** @class */ (function () {
  75360. function MorphTarget(name, influence) {
  75361. if (influence === void 0) { influence = 0; }
  75362. this.name = name;
  75363. this.animations = new Array();
  75364. this._positions = null;
  75365. this._normals = null;
  75366. this._tangents = null;
  75367. this.onInfluenceChanged = new BABYLON.Observable();
  75368. this.influence = influence;
  75369. }
  75370. Object.defineProperty(MorphTarget.prototype, "influence", {
  75371. get: function () {
  75372. return this._influence;
  75373. },
  75374. set: function (influence) {
  75375. if (this._influence === influence) {
  75376. return;
  75377. }
  75378. var previous = this._influence;
  75379. this._influence = influence;
  75380. if (this.onInfluenceChanged.hasObservers) {
  75381. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  75382. }
  75383. },
  75384. enumerable: true,
  75385. configurable: true
  75386. });
  75387. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  75388. get: function () {
  75389. return !!this._positions;
  75390. },
  75391. enumerable: true,
  75392. configurable: true
  75393. });
  75394. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  75395. get: function () {
  75396. return !!this._normals;
  75397. },
  75398. enumerable: true,
  75399. configurable: true
  75400. });
  75401. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  75402. get: function () {
  75403. return !!this._tangents;
  75404. },
  75405. enumerable: true,
  75406. configurable: true
  75407. });
  75408. MorphTarget.prototype.setPositions = function (data) {
  75409. this._positions = data;
  75410. };
  75411. MorphTarget.prototype.getPositions = function () {
  75412. return this._positions;
  75413. };
  75414. MorphTarget.prototype.setNormals = function (data) {
  75415. this._normals = data;
  75416. };
  75417. MorphTarget.prototype.getNormals = function () {
  75418. return this._normals;
  75419. };
  75420. MorphTarget.prototype.setTangents = function (data) {
  75421. this._tangents = data;
  75422. };
  75423. MorphTarget.prototype.getTangents = function () {
  75424. return this._tangents;
  75425. };
  75426. /**
  75427. * Serializes the current target into a Serialization object.
  75428. * Returns the serialized object.
  75429. */
  75430. MorphTarget.prototype.serialize = function () {
  75431. var serializationObject = {};
  75432. serializationObject.name = this.name;
  75433. serializationObject.influence = this.influence;
  75434. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  75435. if (this.hasNormals) {
  75436. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  75437. }
  75438. if (this.hasTangents) {
  75439. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  75440. }
  75441. // Animations
  75442. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  75443. return serializationObject;
  75444. };
  75445. // Statics
  75446. MorphTarget.Parse = function (serializationObject) {
  75447. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  75448. result.setPositions(serializationObject.positions);
  75449. if (serializationObject.normals) {
  75450. result.setNormals(serializationObject.normals);
  75451. }
  75452. if (serializationObject.tangents) {
  75453. result.setTangents(serializationObject.tangents);
  75454. }
  75455. // Animations
  75456. if (serializationObject.animations) {
  75457. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  75458. var parsedAnimation = serializationObject.animations[animationIndex];
  75459. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  75460. }
  75461. }
  75462. return result;
  75463. };
  75464. MorphTarget.FromMesh = function (mesh, name, influence) {
  75465. if (!name) {
  75466. name = mesh.name;
  75467. }
  75468. var result = new MorphTarget(name, influence);
  75469. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  75470. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75471. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  75472. }
  75473. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  75474. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  75475. }
  75476. return result;
  75477. };
  75478. return MorphTarget;
  75479. }());
  75480. BABYLON.MorphTarget = MorphTarget;
  75481. })(BABYLON || (BABYLON = {}));
  75482. //# sourceMappingURL=babylon.morphTarget.js.map
  75483. var BABYLON;
  75484. (function (BABYLON) {
  75485. var MorphTargetManager = /** @class */ (function () {
  75486. function MorphTargetManager(scene) {
  75487. if (scene === void 0) { scene = null; }
  75488. this._targets = new Array();
  75489. this._targetObservable = new Array();
  75490. this._activeTargets = new BABYLON.SmartArray(16);
  75491. this._supportsNormals = false;
  75492. this._supportsTangents = false;
  75493. this._vertexCount = 0;
  75494. this._uniqueId = 0;
  75495. this._tempInfluences = new Array();
  75496. if (!scene) {
  75497. scene = BABYLON.Engine.LastCreatedScene;
  75498. }
  75499. this._scene = scene;
  75500. if (this._scene) {
  75501. this._scene.morphTargetManagers.push(this);
  75502. this._uniqueId = this._scene.getUniqueId();
  75503. }
  75504. }
  75505. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  75506. get: function () {
  75507. return this._uniqueId;
  75508. },
  75509. enumerable: true,
  75510. configurable: true
  75511. });
  75512. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  75513. get: function () {
  75514. return this._vertexCount;
  75515. },
  75516. enumerable: true,
  75517. configurable: true
  75518. });
  75519. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  75520. get: function () {
  75521. return this._supportsNormals;
  75522. },
  75523. enumerable: true,
  75524. configurable: true
  75525. });
  75526. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  75527. get: function () {
  75528. return this._supportsTangents;
  75529. },
  75530. enumerable: true,
  75531. configurable: true
  75532. });
  75533. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  75534. get: function () {
  75535. return this._targets.length;
  75536. },
  75537. enumerable: true,
  75538. configurable: true
  75539. });
  75540. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  75541. get: function () {
  75542. return this._activeTargets.length;
  75543. },
  75544. enumerable: true,
  75545. configurable: true
  75546. });
  75547. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  75548. get: function () {
  75549. return this._influences;
  75550. },
  75551. enumerable: true,
  75552. configurable: true
  75553. });
  75554. MorphTargetManager.prototype.getActiveTarget = function (index) {
  75555. return this._activeTargets.data[index];
  75556. };
  75557. MorphTargetManager.prototype.getTarget = function (index) {
  75558. return this._targets[index];
  75559. };
  75560. MorphTargetManager.prototype.addTarget = function (target) {
  75561. var _this = this;
  75562. this._targets.push(target);
  75563. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  75564. _this._syncActiveTargets(needUpdate);
  75565. }));
  75566. this._syncActiveTargets(true);
  75567. };
  75568. MorphTargetManager.prototype.removeTarget = function (target) {
  75569. var index = this._targets.indexOf(target);
  75570. if (index >= 0) {
  75571. this._targets.splice(index, 1);
  75572. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  75573. this._syncActiveTargets(true);
  75574. }
  75575. };
  75576. /**
  75577. * Serializes the current manager into a Serialization object.
  75578. * Returns the serialized object.
  75579. */
  75580. MorphTargetManager.prototype.serialize = function () {
  75581. var serializationObject = {};
  75582. serializationObject.id = this.uniqueId;
  75583. serializationObject.targets = [];
  75584. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  75585. var target = _a[_i];
  75586. serializationObject.targets.push(target.serialize());
  75587. }
  75588. return serializationObject;
  75589. };
  75590. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  75591. var influenceCount = 0;
  75592. this._activeTargets.reset();
  75593. this._supportsNormals = true;
  75594. this._supportsTangents = true;
  75595. this._vertexCount = 0;
  75596. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  75597. var target = _a[_i];
  75598. this._activeTargets.push(target);
  75599. this._tempInfluences[influenceCount++] = target.influence;
  75600. var positions = target.getPositions();
  75601. if (positions) {
  75602. this._supportsNormals = this._supportsNormals && target.hasNormals;
  75603. this._supportsTangents = this._supportsTangents && target.hasTangents;
  75604. var vertexCount = positions.length / 3;
  75605. if (this._vertexCount === 0) {
  75606. this._vertexCount = vertexCount;
  75607. }
  75608. else if (this._vertexCount !== vertexCount) {
  75609. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  75610. return;
  75611. }
  75612. }
  75613. }
  75614. if (!this._influences || this._influences.length !== influenceCount) {
  75615. this._influences = new Float32Array(influenceCount);
  75616. }
  75617. for (var index = 0; index < influenceCount; index++) {
  75618. this._influences[index] = this._tempInfluences[index];
  75619. }
  75620. if (needUpdate && this._scene) {
  75621. // Flag meshes as dirty to resync with the active targets
  75622. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  75623. var mesh = _c[_b];
  75624. if (mesh.morphTargetManager === this) {
  75625. mesh._syncGeometryWithMorphTargetManager();
  75626. }
  75627. }
  75628. }
  75629. };
  75630. // Statics
  75631. MorphTargetManager.Parse = function (serializationObject, scene) {
  75632. var result = new MorphTargetManager(scene);
  75633. result._uniqueId = serializationObject.id;
  75634. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  75635. var targetData = _a[_i];
  75636. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  75637. }
  75638. return result;
  75639. };
  75640. return MorphTargetManager;
  75641. }());
  75642. BABYLON.MorphTargetManager = MorphTargetManager;
  75643. })(BABYLON || (BABYLON = {}));
  75644. //# sourceMappingURL=babylon.morphTargetManager.js.map
  75645. var BABYLON;
  75646. (function (BABYLON) {
  75647. var Octree = /** @class */ (function () {
  75648. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  75649. if (maxDepth === void 0) { maxDepth = 2; }
  75650. this.maxDepth = maxDepth;
  75651. this.dynamicContent = new Array();
  75652. this._maxBlockCapacity = maxBlockCapacity || 64;
  75653. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  75654. this._creationFunc = creationFunc;
  75655. }
  75656. // Methods
  75657. Octree.prototype.update = function (worldMin, worldMax, entries) {
  75658. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  75659. };
  75660. Octree.prototype.addMesh = function (entry) {
  75661. for (var index = 0; index < this.blocks.length; index++) {
  75662. var block = this.blocks[index];
  75663. block.addEntry(entry);
  75664. }
  75665. };
  75666. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  75667. this._selectionContent.reset();
  75668. for (var index = 0; index < this.blocks.length; index++) {
  75669. var block = this.blocks[index];
  75670. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  75671. }
  75672. if (allowDuplicate) {
  75673. this._selectionContent.concat(this.dynamicContent);
  75674. }
  75675. else {
  75676. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75677. }
  75678. return this._selectionContent;
  75679. };
  75680. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  75681. this._selectionContent.reset();
  75682. for (var index = 0; index < this.blocks.length; index++) {
  75683. var block = this.blocks[index];
  75684. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  75685. }
  75686. if (allowDuplicate) {
  75687. this._selectionContent.concat(this.dynamicContent);
  75688. }
  75689. else {
  75690. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75691. }
  75692. return this._selectionContent;
  75693. };
  75694. Octree.prototype.intersectsRay = function (ray) {
  75695. this._selectionContent.reset();
  75696. for (var index = 0; index < this.blocks.length; index++) {
  75697. var block = this.blocks[index];
  75698. block.intersectsRay(ray, this._selectionContent);
  75699. }
  75700. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75701. return this._selectionContent;
  75702. };
  75703. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  75704. target.blocks = new Array();
  75705. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  75706. // Segmenting space
  75707. for (var x = 0; x < 2; x++) {
  75708. for (var y = 0; y < 2; y++) {
  75709. for (var z = 0; z < 2; z++) {
  75710. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  75711. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  75712. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  75713. block.addEntries(entries);
  75714. target.blocks.push(block);
  75715. }
  75716. }
  75717. }
  75718. };
  75719. Octree.CreationFuncForMeshes = function (entry, block) {
  75720. var boundingInfo = entry.getBoundingInfo();
  75721. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75722. block.entries.push(entry);
  75723. }
  75724. };
  75725. Octree.CreationFuncForSubMeshes = function (entry, block) {
  75726. var boundingInfo = entry.getBoundingInfo();
  75727. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75728. block.entries.push(entry);
  75729. }
  75730. };
  75731. return Octree;
  75732. }());
  75733. BABYLON.Octree = Octree;
  75734. })(BABYLON || (BABYLON = {}));
  75735. //# sourceMappingURL=babylon.octree.js.map
  75736. var BABYLON;
  75737. (function (BABYLON) {
  75738. var OctreeBlock = /** @class */ (function () {
  75739. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  75740. this.entries = new Array();
  75741. this._boundingVectors = new Array();
  75742. this._capacity = capacity;
  75743. this._depth = depth;
  75744. this._maxDepth = maxDepth;
  75745. this._creationFunc = creationFunc;
  75746. this._minPoint = minPoint;
  75747. this._maxPoint = maxPoint;
  75748. this._boundingVectors.push(minPoint.clone());
  75749. this._boundingVectors.push(maxPoint.clone());
  75750. this._boundingVectors.push(minPoint.clone());
  75751. this._boundingVectors[2].x = maxPoint.x;
  75752. this._boundingVectors.push(minPoint.clone());
  75753. this._boundingVectors[3].y = maxPoint.y;
  75754. this._boundingVectors.push(minPoint.clone());
  75755. this._boundingVectors[4].z = maxPoint.z;
  75756. this._boundingVectors.push(maxPoint.clone());
  75757. this._boundingVectors[5].z = minPoint.z;
  75758. this._boundingVectors.push(maxPoint.clone());
  75759. this._boundingVectors[6].x = minPoint.x;
  75760. this._boundingVectors.push(maxPoint.clone());
  75761. this._boundingVectors[7].y = minPoint.y;
  75762. }
  75763. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  75764. // Property
  75765. get: function () {
  75766. return this._capacity;
  75767. },
  75768. enumerable: true,
  75769. configurable: true
  75770. });
  75771. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  75772. get: function () {
  75773. return this._minPoint;
  75774. },
  75775. enumerable: true,
  75776. configurable: true
  75777. });
  75778. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  75779. get: function () {
  75780. return this._maxPoint;
  75781. },
  75782. enumerable: true,
  75783. configurable: true
  75784. });
  75785. // Methods
  75786. OctreeBlock.prototype.addEntry = function (entry) {
  75787. if (this.blocks) {
  75788. for (var index = 0; index < this.blocks.length; index++) {
  75789. var block = this.blocks[index];
  75790. block.addEntry(entry);
  75791. }
  75792. return;
  75793. }
  75794. this._creationFunc(entry, this);
  75795. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  75796. this.createInnerBlocks();
  75797. }
  75798. };
  75799. OctreeBlock.prototype.addEntries = function (entries) {
  75800. for (var index = 0; index < entries.length; index++) {
  75801. var mesh = entries[index];
  75802. this.addEntry(mesh);
  75803. }
  75804. };
  75805. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  75806. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  75807. if (this.blocks) {
  75808. for (var index = 0; index < this.blocks.length; index++) {
  75809. var block = this.blocks[index];
  75810. block.select(frustumPlanes, selection, allowDuplicate);
  75811. }
  75812. return;
  75813. }
  75814. if (allowDuplicate) {
  75815. selection.concat(this.entries);
  75816. }
  75817. else {
  75818. selection.concatWithNoDuplicate(this.entries);
  75819. }
  75820. }
  75821. };
  75822. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  75823. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  75824. if (this.blocks) {
  75825. for (var index = 0; index < this.blocks.length; index++) {
  75826. var block = this.blocks[index];
  75827. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  75828. }
  75829. return;
  75830. }
  75831. if (allowDuplicate) {
  75832. selection.concat(this.entries);
  75833. }
  75834. else {
  75835. selection.concatWithNoDuplicate(this.entries);
  75836. }
  75837. }
  75838. };
  75839. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  75840. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  75841. if (this.blocks) {
  75842. for (var index = 0; index < this.blocks.length; index++) {
  75843. var block = this.blocks[index];
  75844. block.intersectsRay(ray, selection);
  75845. }
  75846. return;
  75847. }
  75848. selection.concatWithNoDuplicate(this.entries);
  75849. }
  75850. };
  75851. OctreeBlock.prototype.createInnerBlocks = function () {
  75852. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  75853. };
  75854. return OctreeBlock;
  75855. }());
  75856. BABYLON.OctreeBlock = OctreeBlock;
  75857. })(BABYLON || (BABYLON = {}));
  75858. //# sourceMappingURL=babylon.octreeBlock.js.map
  75859. var BABYLON;
  75860. (function (BABYLON) {
  75861. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  75862. __extends(VRDistortionCorrectionPostProcess, _super);
  75863. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  75864. var _this = _super.call(this, name, "vrDistortionCorrection", [
  75865. 'LensCenter',
  75866. 'Scale',
  75867. 'ScaleIn',
  75868. 'HmdWarpParam'
  75869. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  75870. _this._isRightEye = isRightEye;
  75871. _this._distortionFactors = vrMetrics.distortionK;
  75872. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  75873. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  75874. _this.adaptScaleToCurrentViewport = true;
  75875. _this.onSizeChangedObservable.add(function () {
  75876. _this.aspectRatio = _this.width * .5 / _this.height;
  75877. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  75878. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  75879. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  75880. });
  75881. _this.onApplyObservable.add(function (effect) {
  75882. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  75883. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  75884. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  75885. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  75886. });
  75887. return _this;
  75888. }
  75889. return VRDistortionCorrectionPostProcess;
  75890. }(BABYLON.PostProcess));
  75891. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  75892. })(BABYLON || (BABYLON = {}));
  75893. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  75894. var BABYLON;
  75895. (function (BABYLON) {
  75896. var AnaglyphPostProcess = /** @class */ (function (_super) {
  75897. __extends(AnaglyphPostProcess, _super);
  75898. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  75899. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  75900. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75901. _this.onApplyObservable.add(function (effect) {
  75902. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  75903. });
  75904. return _this;
  75905. }
  75906. return AnaglyphPostProcess;
  75907. }(BABYLON.PostProcess));
  75908. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  75909. })(BABYLON || (BABYLON = {}));
  75910. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  75911. var BABYLON;
  75912. (function (BABYLON) {
  75913. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  75914. __extends(StereoscopicInterlacePostProcess, _super);
  75915. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  75916. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  75917. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75918. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75919. _this.onSizeChangedObservable.add(function () {
  75920. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75921. });
  75922. _this.onApplyObservable.add(function (effect) {
  75923. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  75924. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  75925. });
  75926. return _this;
  75927. }
  75928. return StereoscopicInterlacePostProcess;
  75929. }(BABYLON.PostProcess));
  75930. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  75931. })(BABYLON || (BABYLON = {}));
  75932. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  75933. var BABYLON;
  75934. (function (BABYLON) {
  75935. /**
  75936. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  75937. * Screen rotation is taken into account.
  75938. */
  75939. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  75940. function FreeCameraDeviceOrientationInput() {
  75941. var _this = this;
  75942. this._screenOrientationAngle = 0;
  75943. this._screenQuaternion = new BABYLON.Quaternion();
  75944. this._alpha = 0;
  75945. this._beta = 0;
  75946. this._gamma = 0;
  75947. this._orientationChanged = function () {
  75948. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  75949. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  75950. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  75951. };
  75952. this._deviceOrientation = function (evt) {
  75953. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  75954. _this._beta = evt.beta !== null ? evt.beta : 0;
  75955. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  75956. };
  75957. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  75958. this._orientationChanged();
  75959. }
  75960. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  75961. get: function () {
  75962. return this._camera;
  75963. },
  75964. set: function (camera) {
  75965. this._camera = camera;
  75966. if (this._camera != null && !this._camera.rotationQuaternion) {
  75967. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  75968. }
  75969. },
  75970. enumerable: true,
  75971. configurable: true
  75972. });
  75973. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  75974. window.addEventListener("orientationchange", this._orientationChanged);
  75975. window.addEventListener("deviceorientation", this._deviceOrientation);
  75976. //In certain cases, the attach control is called AFTER orientation was changed,
  75977. //So this is needed.
  75978. this._orientationChanged();
  75979. };
  75980. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  75981. window.removeEventListener("orientationchange", this._orientationChanged);
  75982. window.removeEventListener("deviceorientation", this._deviceOrientation);
  75983. };
  75984. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  75985. //if no device orientation provided, don't update the rotation.
  75986. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  75987. if (!this._alpha)
  75988. return;
  75989. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  75990. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  75991. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  75992. //Mirror on XY Plane
  75993. this._camera.rotationQuaternion.z *= -1;
  75994. this._camera.rotationQuaternion.w *= -1;
  75995. };
  75996. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  75997. return "FreeCameraDeviceOrientationInput";
  75998. };
  75999. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  76000. return "deviceOrientation";
  76001. };
  76002. return FreeCameraDeviceOrientationInput;
  76003. }());
  76004. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  76005. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  76006. })(BABYLON || (BABYLON = {}));
  76007. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  76008. var BABYLON;
  76009. (function (BABYLON) {
  76010. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  76011. function ArcRotateCameraVRDeviceOrientationInput() {
  76012. this.alphaCorrection = 1;
  76013. this.betaCorrection = 1;
  76014. this.gammaCorrection = 1;
  76015. this._alpha = 0;
  76016. this._gamma = 0;
  76017. this._dirty = false;
  76018. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  76019. }
  76020. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  76021. this.camera.attachControl(element, noPreventDefault);
  76022. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  76023. };
  76024. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  76025. if (evt.alpha !== null) {
  76026. this._alpha = +evt.alpha | 0;
  76027. }
  76028. if (evt.gamma !== null) {
  76029. this._gamma = +evt.gamma | 0;
  76030. }
  76031. this._dirty = true;
  76032. };
  76033. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  76034. if (this._dirty) {
  76035. this._dirty = false;
  76036. if (this._gamma < 0) {
  76037. this._gamma = 180 + this._gamma;
  76038. }
  76039. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  76040. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  76041. }
  76042. };
  76043. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  76044. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  76045. };
  76046. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  76047. return "ArcRotateCameraVRDeviceOrientationInput";
  76048. };
  76049. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  76050. return "VRDeviceOrientation";
  76051. };
  76052. return ArcRotateCameraVRDeviceOrientationInput;
  76053. }());
  76054. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  76055. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  76056. })(BABYLON || (BABYLON = {}));
  76057. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  76058. var BABYLON;
  76059. (function (BABYLON) {
  76060. var VRCameraMetrics = /** @class */ (function () {
  76061. function VRCameraMetrics() {
  76062. this.compensateDistortion = true;
  76063. }
  76064. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  76065. get: function () {
  76066. return this.hResolution / (2 * this.vResolution);
  76067. },
  76068. enumerable: true,
  76069. configurable: true
  76070. });
  76071. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  76072. get: function () {
  76073. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  76074. },
  76075. enumerable: true,
  76076. configurable: true
  76077. });
  76078. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  76079. get: function () {
  76080. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  76081. var h = (4 * meters) / this.hScreenSize;
  76082. return BABYLON.Matrix.Translation(h, 0, 0);
  76083. },
  76084. enumerable: true,
  76085. configurable: true
  76086. });
  76087. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  76088. get: function () {
  76089. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  76090. var h = (4 * meters) / this.hScreenSize;
  76091. return BABYLON.Matrix.Translation(-h, 0, 0);
  76092. },
  76093. enumerable: true,
  76094. configurable: true
  76095. });
  76096. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  76097. get: function () {
  76098. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  76099. },
  76100. enumerable: true,
  76101. configurable: true
  76102. });
  76103. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  76104. get: function () {
  76105. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  76106. },
  76107. enumerable: true,
  76108. configurable: true
  76109. });
  76110. VRCameraMetrics.GetDefault = function () {
  76111. var result = new VRCameraMetrics();
  76112. result.hResolution = 1280;
  76113. result.vResolution = 800;
  76114. result.hScreenSize = 0.149759993;
  76115. result.vScreenSize = 0.0935999975;
  76116. result.vScreenCenter = 0.0467999987;
  76117. result.eyeToScreenDistance = 0.0410000011;
  76118. result.lensSeparationDistance = 0.0635000020;
  76119. result.interpupillaryDistance = 0.0640000030;
  76120. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  76121. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  76122. result.postProcessScaleFactor = 1.714605507808412;
  76123. result.lensCenterOffset = 0.151976421;
  76124. return result;
  76125. };
  76126. return VRCameraMetrics;
  76127. }());
  76128. BABYLON.VRCameraMetrics = VRCameraMetrics;
  76129. })(BABYLON || (BABYLON = {}));
  76130. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  76131. var BABYLON;
  76132. (function (BABYLON) {
  76133. /**
  76134. * This represents a WebVR camera.
  76135. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  76136. * @example http://doc.babylonjs.com/how_to/webvr_camera
  76137. */
  76138. var WebVRFreeCamera = /** @class */ (function (_super) {
  76139. __extends(WebVRFreeCamera, _super);
  76140. /**
  76141. * Instantiates a WebVRFreeCamera.
  76142. * @param name The name of the WebVRFreeCamera
  76143. * @param position The starting anchor position for the camera
  76144. * @param scene The scene the camera belongs to
  76145. * @param webVROptions a set of customizable options for the webVRCamera
  76146. */
  76147. function WebVRFreeCamera(name, position, scene, webVROptions) {
  76148. if (webVROptions === void 0) { webVROptions = {}; }
  76149. var _this = _super.call(this, name, position, scene) || this;
  76150. _this.webVROptions = webVROptions;
  76151. /**
  76152. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  76153. */
  76154. _this._vrDevice = null;
  76155. /**
  76156. * The rawPose of the vrDevice.
  76157. */
  76158. _this.rawPose = null;
  76159. _this._specsVersion = "1.1";
  76160. _this._attached = false;
  76161. _this._descendants = [];
  76162. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  76163. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  76164. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  76165. _this._standingMatrix = null;
  76166. /**
  76167. * Represents device position in babylon space.
  76168. */
  76169. _this.devicePosition = BABYLON.Vector3.Zero();
  76170. /**
  76171. * Represents device rotation in babylon space.
  76172. */
  76173. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  76174. /**
  76175. * The scale of the device to be used when translating from device space to babylon space.
  76176. */
  76177. _this.deviceScaleFactor = 1;
  76178. _this._deviceToWorld = BABYLON.Matrix.Identity();
  76179. _this._worldToDevice = BABYLON.Matrix.Identity();
  76180. /**
  76181. * References to the webVR controllers for the vrDevice.
  76182. */
  76183. _this.controllers = [];
  76184. /**
  76185. * Emits an event when a controller is attached.
  76186. */
  76187. _this.onControllersAttachedObservable = new BABYLON.Observable();
  76188. /**
  76189. * Emits an event when a controller's mesh has been loaded;
  76190. */
  76191. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  76192. /**
  76193. * If the rig cameras be used as parent instead of this camera.
  76194. */
  76195. _this.rigParenting = true;
  76196. _this._defaultHeight = undefined;
  76197. _this._workingVector = BABYLON.Vector3.Zero();
  76198. _this._oneVector = BABYLON.Vector3.One();
  76199. _this._workingMatrix = BABYLON.Matrix.Identity();
  76200. _this._cache.position = BABYLON.Vector3.Zero();
  76201. if (webVROptions.defaultHeight) {
  76202. _this._defaultHeight = webVROptions.defaultHeight;
  76203. _this.position.y = _this._defaultHeight;
  76204. }
  76205. _this.minZ = 0.1;
  76206. //legacy support - the compensation boolean was removed.
  76207. if (arguments.length === 5) {
  76208. _this.webVROptions = arguments[4];
  76209. }
  76210. // default webVR options
  76211. if (_this.webVROptions.trackPosition == undefined) {
  76212. _this.webVROptions.trackPosition = true;
  76213. }
  76214. if (_this.webVROptions.controllerMeshes == undefined) {
  76215. _this.webVROptions.controllerMeshes = true;
  76216. }
  76217. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  76218. _this.webVROptions.defaultLightingOnControllers = true;
  76219. }
  76220. _this.rotationQuaternion = new BABYLON.Quaternion();
  76221. if (_this.webVROptions && _this.webVROptions.positionScale) {
  76222. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  76223. }
  76224. //enable VR
  76225. var engine = _this.getEngine();
  76226. _this._onVREnabled = function (success) { if (success) {
  76227. _this.initControllers();
  76228. } };
  76229. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  76230. engine.initWebVR().add(function (event) {
  76231. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  76232. return;
  76233. }
  76234. _this._vrDevice = event.vrDisplay;
  76235. //reset the rig parameters.
  76236. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  76237. if (_this._attached) {
  76238. _this.getEngine().enableVR();
  76239. }
  76240. });
  76241. if (typeof (VRFrameData) !== "undefined")
  76242. _this._frameData = new VRFrameData();
  76243. /**
  76244. * The idea behind the following lines:
  76245. * objects that have the camera as parent should actually have the rig cameras as a parent.
  76246. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  76247. * the second will not show it correctly.
  76248. *
  76249. * To solve this - each object that has the camera as parent will be added to a protected array.
  76250. * When the rig camera renders, it will take this array and set all of those to be its children.
  76251. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  76252. * Amazing!
  76253. */
  76254. scene.onBeforeCameraRenderObservable.add(function (camera) {
  76255. if (camera.parent === _this && _this.rigParenting) {
  76256. _this._descendants = _this.getDescendants(true, function (n) {
  76257. // don't take the cameras or the controllers!
  76258. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  76259. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  76260. return !isController && !isRigCamera;
  76261. });
  76262. _this._descendants.forEach(function (node) {
  76263. node.parent = camera;
  76264. });
  76265. }
  76266. });
  76267. scene.onAfterCameraRenderObservable.add(function (camera) {
  76268. if (camera.parent === _this && _this.rigParenting) {
  76269. _this._descendants.forEach(function (node) {
  76270. node.parent = _this;
  76271. });
  76272. }
  76273. });
  76274. return _this;
  76275. }
  76276. /**
  76277. * Gets the device distance from the ground.
  76278. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  76279. */
  76280. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  76281. if (this._standingMatrix && this._defaultHeight === undefined) {
  76282. // Add standing matrix offset to get real offset from ground in room
  76283. this._standingMatrix.getTranslationToRef(this._workingVector);
  76284. return this._deviceRoomPosition.y + this._workingVector.y;
  76285. }
  76286. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  76287. return this._defaultHeight || 0;
  76288. };
  76289. /**
  76290. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  76291. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  76292. */
  76293. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  76294. var _this = this;
  76295. if (callback === void 0) { callback = function (bool) { }; }
  76296. // Use standing matrix if available
  76297. if (!navigator || !navigator.getVRDisplays) {
  76298. callback(false);
  76299. }
  76300. else {
  76301. navigator.getVRDisplays().then(function (displays) {
  76302. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  76303. callback(false);
  76304. }
  76305. else {
  76306. _this._standingMatrix = new BABYLON.Matrix();
  76307. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  76308. if (!_this.getScene().useRightHandedSystem) {
  76309. [2, 6, 8, 9, 14].forEach(function (num) {
  76310. if (_this._standingMatrix) {
  76311. _this._standingMatrix.m[num] *= -1;
  76312. }
  76313. });
  76314. }
  76315. callback(true);
  76316. }
  76317. });
  76318. }
  76319. };
  76320. /**
  76321. * Disposes the camera
  76322. */
  76323. WebVRFreeCamera.prototype.dispose = function () {
  76324. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  76325. _super.prototype.dispose.call(this);
  76326. };
  76327. /**
  76328. * Gets a vrController by name.
  76329. * @param name The name of the controller to retreive
  76330. * @returns the controller matching the name specified or null if not found
  76331. */
  76332. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  76333. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  76334. var gp = _a[_i];
  76335. if (gp.hand === name) {
  76336. return gp;
  76337. }
  76338. }
  76339. return null;
  76340. };
  76341. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  76342. /**
  76343. * The controller corrisponding to the users left hand.
  76344. */
  76345. get: function () {
  76346. if (!this._leftController) {
  76347. this._leftController = this.getControllerByName("left");
  76348. }
  76349. return this._leftController;
  76350. },
  76351. enumerable: true,
  76352. configurable: true
  76353. });
  76354. ;
  76355. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  76356. /**
  76357. * The controller corrisponding to the users right hand.
  76358. */
  76359. get: function () {
  76360. if (!this._rightController) {
  76361. this._rightController = this.getControllerByName("right");
  76362. }
  76363. return this._rightController;
  76364. },
  76365. enumerable: true,
  76366. configurable: true
  76367. });
  76368. ;
  76369. /**
  76370. * Casts a ray forward from the vrCamera's gaze.
  76371. * @param length Length of the ray (default: 100)
  76372. * @returns the ray corrisponding to the gaze
  76373. */
  76374. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  76375. if (length === void 0) { length = 100; }
  76376. if (this.leftCamera) {
  76377. // Use left eye to avoid computation to compute center on every call
  76378. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  76379. }
  76380. else {
  76381. return _super.prototype.getForwardRay.call(this, length);
  76382. }
  76383. };
  76384. /**
  76385. * Updates the camera based on device's frame data
  76386. */
  76387. WebVRFreeCamera.prototype._checkInputs = function () {
  76388. if (this._vrDevice && this._vrDevice.isPresenting) {
  76389. this._vrDevice.getFrameData(this._frameData);
  76390. this.updateFromDevice(this._frameData.pose);
  76391. }
  76392. _super.prototype._checkInputs.call(this);
  76393. };
  76394. /**
  76395. * Updates the poseControlled values based on the input device pose.
  76396. * @param poseData Pose coming from the device
  76397. */
  76398. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  76399. if (poseData && poseData.orientation) {
  76400. this.rawPose = poseData;
  76401. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  76402. if (this.getScene().useRightHandedSystem) {
  76403. this._deviceRoomRotationQuaternion.z *= -1;
  76404. this._deviceRoomRotationQuaternion.w *= -1;
  76405. }
  76406. if (this.webVROptions.trackPosition && this.rawPose.position) {
  76407. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  76408. if (this.getScene().useRightHandedSystem) {
  76409. this._deviceRoomPosition.z *= -1;
  76410. }
  76411. }
  76412. }
  76413. };
  76414. /**
  76415. * WebVR's attach control will start broadcasting frames to the device.
  76416. * Note that in certain browsers (chrome for example) this function must be called
  76417. * within a user-interaction callback. Example:
  76418. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  76419. *
  76420. * @param element html element to attach the vrDevice to
  76421. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  76422. */
  76423. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  76424. _super.prototype.attachControl.call(this, element, noPreventDefault);
  76425. this._attached = true;
  76426. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  76427. if (this._vrDevice) {
  76428. this.getEngine().enableVR();
  76429. }
  76430. };
  76431. /**
  76432. * Detaches the camera from the html element and disables VR
  76433. *
  76434. * @param element html element to detach from
  76435. */
  76436. WebVRFreeCamera.prototype.detachControl = function (element) {
  76437. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  76438. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  76439. _super.prototype.detachControl.call(this, element);
  76440. this._attached = false;
  76441. this.getEngine().disableVR();
  76442. };
  76443. /**
  76444. * @returns the name of this class
  76445. */
  76446. WebVRFreeCamera.prototype.getClassName = function () {
  76447. return "WebVRFreeCamera";
  76448. };
  76449. /**
  76450. * Calls resetPose on the vrDisplay
  76451. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  76452. */
  76453. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  76454. //uses the vrDisplay's "resetPose()".
  76455. //pitch and roll won't be affected.
  76456. this._vrDevice.resetPose();
  76457. };
  76458. /**
  76459. * Updates the rig cameras (left and right eye)
  76460. */
  76461. WebVRFreeCamera.prototype._updateRigCameras = function () {
  76462. var camLeft = this._rigCameras[0];
  76463. var camRight = this._rigCameras[1];
  76464. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  76465. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  76466. camLeft.position.copyFrom(this._deviceRoomPosition);
  76467. camRight.position.copyFrom(this._deviceRoomPosition);
  76468. };
  76469. /**
  76470. * Updates the cached values of the camera
  76471. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  76472. */
  76473. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  76474. var _this = this;
  76475. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  76476. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  76477. if (!this.updateCacheCalled) {
  76478. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  76479. this.updateCacheCalled = true;
  76480. this.update();
  76481. }
  76482. // Set working vector to the device position in room space rotated by the new rotation
  76483. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  76484. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  76485. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  76486. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  76487. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  76488. // Add translation from anchor position
  76489. this._deviceToWorld.getTranslationToRef(this._workingVector);
  76490. this._workingVector.addInPlace(this.position);
  76491. this._workingVector.subtractInPlace(this._cache.position);
  76492. this._deviceToWorld.setTranslation(this._workingVector);
  76493. // Set an inverted matrix to be used when updating the camera
  76494. this._deviceToWorld.invertToRef(this._worldToDevice);
  76495. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  76496. this.controllers.forEach(function (controller) {
  76497. controller._deviceToWorld = _this._deviceToWorld;
  76498. controller.update();
  76499. });
  76500. }
  76501. if (!ignoreParentClass) {
  76502. _super.prototype._updateCache.call(this);
  76503. }
  76504. this.updateCacheCalled = false;
  76505. };
  76506. /**
  76507. * Updates the current device position and rotation in the babylon world
  76508. */
  76509. WebVRFreeCamera.prototype.update = function () {
  76510. // Get current device position in babylon world
  76511. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  76512. // Get current device rotation in babylon world
  76513. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  76514. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  76515. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  76516. _super.prototype.update.call(this);
  76517. };
  76518. /**
  76519. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  76520. * @returns an identity matrix
  76521. */
  76522. WebVRFreeCamera.prototype._getViewMatrix = function () {
  76523. return BABYLON.Matrix.Identity();
  76524. };
  76525. /**
  76526. * This function is called by the two RIG cameras.
  76527. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  76528. */
  76529. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  76530. var _this = this;
  76531. //WebVR 1.1
  76532. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  76533. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  76534. if (!this.getScene().useRightHandedSystem) {
  76535. [2, 6, 8, 9, 14].forEach(function (num) {
  76536. _this._webvrViewMatrix.m[num] *= -1;
  76537. });
  76538. }
  76539. // update the camera rotation matrix
  76540. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  76541. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  76542. // Computing target and final matrix
  76543. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  76544. var parentCamera = this._cameraRigParams["parentCamera"];
  76545. // should the view matrix be updated with scale and position offset?
  76546. if (parentCamera.deviceScaleFactor !== 1) {
  76547. this._webvrViewMatrix.invert();
  76548. // scale the position, if set
  76549. if (parentCamera.deviceScaleFactor) {
  76550. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  76551. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  76552. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  76553. }
  76554. this._webvrViewMatrix.invert();
  76555. }
  76556. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  76557. return this._webvrViewMatrix;
  76558. };
  76559. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  76560. var _this = this;
  76561. var parentCamera = this.parent;
  76562. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  76563. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  76564. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  76565. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  76566. //babylon compatible matrix
  76567. if (!this.getScene().useRightHandedSystem) {
  76568. [8, 9, 10, 11].forEach(function (num) {
  76569. _this._projectionMatrix.m[num] *= -1;
  76570. });
  76571. }
  76572. return this._projectionMatrix;
  76573. };
  76574. /**
  76575. * Initializes the controllers and their meshes
  76576. */
  76577. WebVRFreeCamera.prototype.initControllers = function () {
  76578. var _this = this;
  76579. this.controllers = [];
  76580. var manager = this.getScene().gamepadManager;
  76581. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  76582. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  76583. var webVrController = gamepad;
  76584. if (webVrController.defaultModel) {
  76585. webVrController.defaultModel.setEnabled(false);
  76586. }
  76587. if (webVrController.hand === "right") {
  76588. _this._rightController = null;
  76589. }
  76590. if (webVrController.hand === "left") {
  76591. _this._rightController = null;
  76592. }
  76593. var controllerIndex = _this.controllers.indexOf(webVrController);
  76594. if (controllerIndex !== -1) {
  76595. _this.controllers.splice(controllerIndex, 1);
  76596. }
  76597. }
  76598. });
  76599. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  76600. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  76601. var webVrController_1 = gamepad;
  76602. webVrController_1._deviceToWorld = _this._deviceToWorld;
  76603. if (_this.webVROptions.controllerMeshes) {
  76604. if (webVrController_1.defaultModel) {
  76605. webVrController_1.defaultModel.setEnabled(true);
  76606. }
  76607. else {
  76608. // Load the meshes
  76609. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  76610. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  76611. if (_this.webVROptions.defaultLightingOnControllers) {
  76612. if (!_this._lightOnControllers) {
  76613. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  76614. }
  76615. var activateLightOnSubMeshes_1 = function (mesh, light) {
  76616. var children = mesh.getChildren();
  76617. if (children.length !== 0) {
  76618. children.forEach(function (mesh) {
  76619. light.includedOnlyMeshes.push(mesh);
  76620. activateLightOnSubMeshes_1(mesh, light);
  76621. });
  76622. }
  76623. };
  76624. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  76625. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  76626. }
  76627. });
  76628. }
  76629. }
  76630. webVrController_1.attachToPoseControlledCamera(_this);
  76631. // since this is async - sanity check. Is the controller already stored?
  76632. if (_this.controllers.indexOf(webVrController_1) === -1) {
  76633. //add to the controllers array
  76634. _this.controllers.push(webVrController_1);
  76635. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  76636. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  76637. // So we're overriding setting left & right manually to be sure
  76638. var firstViveWandDetected = false;
  76639. for (var i = 0; i < _this.controllers.length; i++) {
  76640. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  76641. if (!firstViveWandDetected) {
  76642. firstViveWandDetected = true;
  76643. _this.controllers[i].hand = "left";
  76644. }
  76645. else {
  76646. _this.controllers[i].hand = "right";
  76647. }
  76648. }
  76649. }
  76650. //did we find enough controllers? Great! let the developer know.
  76651. if (_this.controllers.length >= 2) {
  76652. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  76653. }
  76654. }
  76655. }
  76656. });
  76657. };
  76658. return WebVRFreeCamera;
  76659. }(BABYLON.FreeCamera));
  76660. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  76661. })(BABYLON || (BABYLON = {}));
  76662. //# sourceMappingURL=babylon.webVRCamera.js.map
  76663. var BABYLON;
  76664. (function (BABYLON) {
  76665. // We're mainly based on the logic defined into the FreeCamera code
  76666. /**
  76667. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  76668. * being tilted forward or back and left or right.
  76669. */
  76670. var DeviceOrientationCamera = /** @class */ (function (_super) {
  76671. __extends(DeviceOrientationCamera, _super);
  76672. /**
  76673. * Creates a new device orientation camera. @see DeviceOrientationCamera
  76674. * @param name The name of the camera
  76675. * @param position The start position camera
  76676. * @param scene The scene the camera belongs to
  76677. */
  76678. function DeviceOrientationCamera(name, position, scene) {
  76679. var _this = _super.call(this, name, position, scene) || this;
  76680. _this._quaternionCache = new BABYLON.Quaternion();
  76681. _this.inputs.addDeviceOrientation();
  76682. return _this;
  76683. }
  76684. /**
  76685. * Gets the current instance class name ("DeviceOrientationCamera").
  76686. * This helps avoiding instanceof at run time.
  76687. * @returns the class name
  76688. */
  76689. DeviceOrientationCamera.prototype.getClassName = function () {
  76690. return "DeviceOrientationCamera";
  76691. };
  76692. /**
  76693. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  76694. */
  76695. DeviceOrientationCamera.prototype._checkInputs = function () {
  76696. _super.prototype._checkInputs.call(this);
  76697. this._quaternionCache.copyFrom(this.rotationQuaternion);
  76698. if (this._initialQuaternion) {
  76699. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76700. }
  76701. };
  76702. /**
  76703. * Reset the camera to its default orientation on the specified axis only.
  76704. * @param axis The axis to reset
  76705. */
  76706. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  76707. var _this = this;
  76708. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  76709. //can only work if this camera has a rotation quaternion already.
  76710. if (!this.rotationQuaternion)
  76711. return;
  76712. if (!this._initialQuaternion) {
  76713. this._initialQuaternion = new BABYLON.Quaternion();
  76714. }
  76715. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  76716. ['x', 'y', 'z'].forEach(function (axisName) {
  76717. if (!axis[axisName]) {
  76718. _this._initialQuaternion[axisName] = 0;
  76719. }
  76720. else {
  76721. _this._initialQuaternion[axisName] *= -1;
  76722. }
  76723. });
  76724. this._initialQuaternion.normalize();
  76725. //force rotation update
  76726. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76727. };
  76728. return DeviceOrientationCamera;
  76729. }(BABYLON.FreeCamera));
  76730. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  76731. })(BABYLON || (BABYLON = {}));
  76732. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  76733. var BABYLON;
  76734. (function (BABYLON) {
  76735. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  76736. __extends(VRDeviceOrientationFreeCamera, _super);
  76737. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76738. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76739. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76740. var _this = _super.call(this, name, position, scene) || this;
  76741. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76742. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76743. return _this;
  76744. }
  76745. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  76746. return "VRDeviceOrientationFreeCamera";
  76747. };
  76748. return VRDeviceOrientationFreeCamera;
  76749. }(BABYLON.DeviceOrientationCamera));
  76750. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  76751. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  76752. __extends(VRDeviceOrientationGamepadCamera, _super);
  76753. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76754. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76755. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76756. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  76757. _this.inputs.addGamepad();
  76758. return _this;
  76759. }
  76760. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  76761. return "VRDeviceOrientationGamepadCamera";
  76762. };
  76763. return VRDeviceOrientationGamepadCamera;
  76764. }(VRDeviceOrientationFreeCamera));
  76765. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  76766. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  76767. __extends(VRDeviceOrientationArcRotateCamera, _super);
  76768. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  76769. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76770. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76771. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76772. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76773. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76774. _this.inputs.addVRDeviceOrientation();
  76775. return _this;
  76776. }
  76777. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  76778. return "VRDeviceOrientationArcRotateCamera";
  76779. };
  76780. return VRDeviceOrientationArcRotateCamera;
  76781. }(BABYLON.ArcRotateCamera));
  76782. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  76783. })(BABYLON || (BABYLON = {}));
  76784. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  76785. var BABYLON;
  76786. (function (BABYLON) {
  76787. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  76788. __extends(AnaglyphFreeCamera, _super);
  76789. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  76790. var _this = _super.call(this, name, position, scene) || this;
  76791. _this.interaxialDistance = interaxialDistance;
  76792. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76793. return _this;
  76794. }
  76795. AnaglyphFreeCamera.prototype.getClassName = function () {
  76796. return "AnaglyphFreeCamera";
  76797. };
  76798. return AnaglyphFreeCamera;
  76799. }(BABYLON.FreeCamera));
  76800. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  76801. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  76802. __extends(AnaglyphArcRotateCamera, _super);
  76803. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  76804. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76805. _this.interaxialDistance = interaxialDistance;
  76806. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76807. return _this;
  76808. }
  76809. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  76810. return "AnaglyphArcRotateCamera";
  76811. };
  76812. return AnaglyphArcRotateCamera;
  76813. }(BABYLON.ArcRotateCamera));
  76814. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  76815. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  76816. __extends(AnaglyphGamepadCamera, _super);
  76817. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  76818. var _this = _super.call(this, name, position, scene) || this;
  76819. _this.interaxialDistance = interaxialDistance;
  76820. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76821. return _this;
  76822. }
  76823. AnaglyphGamepadCamera.prototype.getClassName = function () {
  76824. return "AnaglyphGamepadCamera";
  76825. };
  76826. return AnaglyphGamepadCamera;
  76827. }(BABYLON.GamepadCamera));
  76828. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  76829. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  76830. __extends(AnaglyphUniversalCamera, _super);
  76831. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  76832. var _this = _super.call(this, name, position, scene) || this;
  76833. _this.interaxialDistance = interaxialDistance;
  76834. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76835. return _this;
  76836. }
  76837. AnaglyphUniversalCamera.prototype.getClassName = function () {
  76838. return "AnaglyphUniversalCamera";
  76839. };
  76840. return AnaglyphUniversalCamera;
  76841. }(BABYLON.UniversalCamera));
  76842. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  76843. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  76844. __extends(StereoscopicFreeCamera, _super);
  76845. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76846. var _this = _super.call(this, name, position, scene) || this;
  76847. _this.interaxialDistance = interaxialDistance;
  76848. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76849. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76850. return _this;
  76851. }
  76852. StereoscopicFreeCamera.prototype.getClassName = function () {
  76853. return "StereoscopicFreeCamera";
  76854. };
  76855. return StereoscopicFreeCamera;
  76856. }(BABYLON.FreeCamera));
  76857. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  76858. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  76859. __extends(StereoscopicArcRotateCamera, _super);
  76860. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  76861. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76862. _this.interaxialDistance = interaxialDistance;
  76863. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76864. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76865. return _this;
  76866. }
  76867. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  76868. return "StereoscopicArcRotateCamera";
  76869. };
  76870. return StereoscopicArcRotateCamera;
  76871. }(BABYLON.ArcRotateCamera));
  76872. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  76873. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  76874. __extends(StereoscopicGamepadCamera, _super);
  76875. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76876. var _this = _super.call(this, name, position, scene) || this;
  76877. _this.interaxialDistance = interaxialDistance;
  76878. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76879. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76880. return _this;
  76881. }
  76882. StereoscopicGamepadCamera.prototype.getClassName = function () {
  76883. return "StereoscopicGamepadCamera";
  76884. };
  76885. return StereoscopicGamepadCamera;
  76886. }(BABYLON.GamepadCamera));
  76887. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  76888. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  76889. __extends(StereoscopicUniversalCamera, _super);
  76890. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76891. var _this = _super.call(this, name, position, scene) || this;
  76892. _this.interaxialDistance = interaxialDistance;
  76893. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76894. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76895. return _this;
  76896. }
  76897. StereoscopicUniversalCamera.prototype.getClassName = function () {
  76898. return "StereoscopicUniversalCamera";
  76899. };
  76900. return StereoscopicUniversalCamera;
  76901. }(BABYLON.UniversalCamera));
  76902. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  76903. })(BABYLON || (BABYLON = {}));
  76904. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  76905. var BABYLON;
  76906. (function (BABYLON) {
  76907. /**
  76908. * Helps to quickly add VR support to an existing scene.
  76909. * See http://doc.babylonjs.com/how_to/webvr_helper
  76910. */
  76911. var VRExperienceHelper = /** @class */ (function () {
  76912. /**
  76913. * Instantiates a VRExperienceHelper.
  76914. * Helps to quickly add VR support to an existing scene.
  76915. * @param scene The scene the VRExperienceHelper belongs to.
  76916. * @param webVROptions Options to modify the vr experience helper's behavior.
  76917. */
  76918. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  76919. if (webVROptions === void 0) { webVROptions = {}; }
  76920. var _this = this;
  76921. this.webVROptions = webVROptions;
  76922. // Can the system support WebVR, even if a headset isn't plugged in?
  76923. this._webVRsupported = false;
  76924. // If WebVR is supported, is a headset plugged in and are we ready to present?
  76925. this._webVRready = false;
  76926. // Are we waiting for the requestPresent callback to complete?
  76927. this._webVRrequesting = false;
  76928. // Are we presenting to the headset right now?
  76929. this._webVRpresenting = false;
  76930. // Are we presenting in the fullscreen fallback?
  76931. this._fullscreenVRpresenting = false;
  76932. /**
  76933. * Observable raised when entering VR.
  76934. */
  76935. this.onEnteringVRObservable = new BABYLON.Observable();
  76936. /**
  76937. * Observable raised when exiting VR.
  76938. */
  76939. this.onExitingVRObservable = new BABYLON.Observable();
  76940. /**
  76941. * Observable raised when controller mesh is loaded.
  76942. */
  76943. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  76944. this._useCustomVRButton = false;
  76945. this._teleportationRequested = false;
  76946. this._teleportationEnabledOnLeftController = false;
  76947. this._teleportationEnabledOnRightController = false;
  76948. this._interactionsEnabledOnLeftController = false;
  76949. this._interactionsEnabledOnRightController = false;
  76950. this._leftControllerReady = false;
  76951. this._rightControllerReady = false;
  76952. this._floorMeshesCollection = [];
  76953. this._teleportationAllowed = false;
  76954. this._rotationAllowed = true;
  76955. this._teleportationRequestInitiated = false;
  76956. this._teleportationBackRequestInitiated = false;
  76957. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  76958. this._rotationRightAsked = false;
  76959. this._rotationLeftAsked = false;
  76960. this._isDefaultTeleportationTarget = true;
  76961. this._teleportationFillColor = "#444444";
  76962. this._teleportationBorderColor = "#FFFFFF";
  76963. this._rotationAngle = 0;
  76964. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  76965. this._padSensibilityUp = 0.65;
  76966. this._padSensibilityDown = 0.35;
  76967. /**
  76968. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  76969. */
  76970. this.onNewMeshSelected = new BABYLON.Observable();
  76971. /**
  76972. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  76973. */
  76974. this.onNewMeshPicked = new BABYLON.Observable();
  76975. /**
  76976. * Observable raised before camera teleportation
  76977. */
  76978. this.onBeforeCameraTeleport = new BABYLON.Observable();
  76979. /**
  76980. * Observable raised after camera teleportation
  76981. */
  76982. this.onAfterCameraTeleport = new BABYLON.Observable();
  76983. /**
  76984. * Observable raised when current selected mesh gets unselected
  76985. */
  76986. this.onSelectedMeshUnselected = new BABYLON.Observable();
  76987. /**
  76988. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  76989. */
  76990. this.teleportationEnabled = true;
  76991. this._pointerDownOnMeshAsked = false;
  76992. this._isActionableMesh = false;
  76993. this._teleportationInitialized = false;
  76994. this._interactionsEnabled = false;
  76995. this._interactionsRequested = false;
  76996. this._displayGaze = true;
  76997. this._displayLaserPointer = true;
  76998. this._dpadPressed = true;
  76999. this._onResize = function () {
  77000. _this.moveButtonToBottomRight();
  77001. if (_this._fullscreenVRpresenting && _this._webVRready) {
  77002. _this.exitVR();
  77003. }
  77004. };
  77005. this._onFullscreenChange = function () {
  77006. if (document.fullscreen !== undefined) {
  77007. _this._fullscreenVRpresenting = document.fullscreen;
  77008. }
  77009. else if (document.mozFullScreen !== undefined) {
  77010. _this._fullscreenVRpresenting = document.mozFullScreen;
  77011. }
  77012. else if (document.webkitIsFullScreen !== undefined) {
  77013. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  77014. }
  77015. else if (document.msIsFullScreen !== undefined) {
  77016. _this._fullscreenVRpresenting = document.msIsFullScreen;
  77017. }
  77018. if (!_this._fullscreenVRpresenting && _this._canvas) {
  77019. _this.exitVR();
  77020. if (!_this._useCustomVRButton) {
  77021. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  77022. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  77023. }
  77024. }
  77025. };
  77026. this.beforeRender = function () {
  77027. _this._castRayAndSelectObject();
  77028. };
  77029. this._onNewGamepadConnected = function (gamepad) {
  77030. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77031. if (gamepad.leftStick) {
  77032. gamepad.onleftstickchanged(function (stickValues) {
  77033. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  77034. // Listening to classic/xbox gamepad only if no VR controller is active
  77035. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  77036. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  77037. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  77038. _this._checkTeleportWithRay(stickValues);
  77039. _this._checkTeleportBackwards(stickValues);
  77040. }
  77041. }
  77042. });
  77043. }
  77044. if (gamepad.rightStick) {
  77045. gamepad.onrightstickchanged(function (stickValues) {
  77046. if (_this._teleportationInitialized) {
  77047. _this._checkRotate(stickValues);
  77048. }
  77049. });
  77050. }
  77051. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  77052. gamepad.onbuttondown(function (buttonPressed) {
  77053. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  77054. _this._selectionPointerDown();
  77055. }
  77056. });
  77057. gamepad.onbuttonup(function (buttonPressed) {
  77058. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  77059. _this._selectionPointerUp();
  77060. }
  77061. });
  77062. }
  77063. }
  77064. else {
  77065. var webVRController = gamepad;
  77066. _this._tryEnableInteractionOnController(webVRController);
  77067. }
  77068. };
  77069. // 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
  77070. this._tryEnableInteractionOnController = function (webVRController) {
  77071. if (webVRController.hand === "left") {
  77072. _this._leftControllerReady = true;
  77073. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  77074. _this._enableInteractionOnController(webVRController);
  77075. }
  77076. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  77077. _this._enableTeleportationOnController(webVRController);
  77078. }
  77079. }
  77080. if (webVRController.hand === "right") {
  77081. _this._rightControllerReady = true;
  77082. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  77083. _this._enableInteractionOnController(webVRController);
  77084. }
  77085. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  77086. _this._enableTeleportationOnController(webVRController);
  77087. }
  77088. }
  77089. };
  77090. this._onNewGamepadDisconnected = function (gamepad) {
  77091. if (gamepad instanceof BABYLON.WebVRController) {
  77092. if (gamepad.hand === "left") {
  77093. _this._interactionsEnabledOnLeftController = false;
  77094. _this._teleportationEnabledOnLeftController = false;
  77095. _this._leftControllerReady = false;
  77096. if (_this._leftLaserPointer) {
  77097. _this._leftLaserPointer.dispose();
  77098. }
  77099. }
  77100. if (gamepad.hand === "right") {
  77101. _this._interactionsEnabledOnRightController = false;
  77102. _this._teleportationEnabledOnRightController = false;
  77103. _this._rightControllerReady = false;
  77104. if (_this._rightLaserPointer) {
  77105. _this._rightLaserPointer.dispose();
  77106. }
  77107. }
  77108. }
  77109. };
  77110. this._workingVector = BABYLON.Vector3.Zero();
  77111. this._workingQuaternion = BABYLON.Quaternion.Identity();
  77112. this._workingMatrix = BABYLON.Matrix.Identity();
  77113. this._scene = scene;
  77114. this._canvas = scene.getEngine().getRenderingCanvas();
  77115. // Parse options
  77116. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  77117. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  77118. }
  77119. if (webVROptions.createDeviceOrientationCamera === undefined) {
  77120. webVROptions.createDeviceOrientationCamera = true;
  77121. }
  77122. if (webVROptions.defaultHeight === undefined) {
  77123. webVROptions.defaultHeight = 1.7;
  77124. }
  77125. if (webVROptions.useCustomVRButton) {
  77126. this._useCustomVRButton = true;
  77127. if (webVROptions.customVRButton) {
  77128. this._btnVR = webVROptions.customVRButton;
  77129. }
  77130. }
  77131. if (webVROptions.rayLength) {
  77132. this._rayLength = webVROptions.rayLength;
  77133. }
  77134. this._defaultHeight = webVROptions.defaultHeight;
  77135. // Set position
  77136. if (this._scene.activeCamera) {
  77137. this._position = this._scene.activeCamera.position.clone();
  77138. }
  77139. else {
  77140. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  77141. }
  77142. // Set non-vr camera
  77143. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  77144. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  77145. // Copy data from existing camera
  77146. if (this._scene.activeCamera) {
  77147. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  77148. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  77149. // Set rotation from previous camera
  77150. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  77151. var targetCamera = this._scene.activeCamera;
  77152. if (targetCamera.rotationQuaternion) {
  77153. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  77154. }
  77155. else {
  77156. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  77157. }
  77158. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  77159. }
  77160. }
  77161. this._scene.activeCamera = this._deviceOrientationCamera;
  77162. if (this._canvas) {
  77163. this._scene.activeCamera.attachControl(this._canvas);
  77164. }
  77165. }
  77166. else {
  77167. this._existingCamera = this._scene.activeCamera;
  77168. }
  77169. // Create VR cameras
  77170. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  77171. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  77172. }
  77173. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  77174. this._webVRCamera.useStandingMatrix();
  77175. // Create default button
  77176. if (!this._useCustomVRButton) {
  77177. this._btnVR = document.createElement("BUTTON");
  77178. this._btnVR.className = "babylonVRicon";
  77179. this._btnVR.id = "babylonVRiconbtn";
  77180. this._btnVR.title = "Click to switch to VR";
  77181. 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) }";
  77182. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  77183. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  77184. // css += ".babylonVRicon.vrdisplaysupported { }";
  77185. // css += ".babylonVRicon.vrdisplayready { }";
  77186. // css += ".babylonVRicon.vrdisplayrequesting { }";
  77187. var style = document.createElement('style');
  77188. style.appendChild(document.createTextNode(css));
  77189. document.getElementsByTagName('head')[0].appendChild(style);
  77190. this.moveButtonToBottomRight();
  77191. }
  77192. // VR button click event
  77193. if (this._btnVR) {
  77194. this._btnVR.addEventListener("click", function () {
  77195. if (!_this.isInVRMode) {
  77196. _this.enterVR();
  77197. }
  77198. else {
  77199. _this.exitVR();
  77200. }
  77201. });
  77202. }
  77203. // Window events
  77204. window.addEventListener("resize", this._onResize);
  77205. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  77206. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  77207. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  77208. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  77209. // Display vr button when headset is connected
  77210. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  77211. this.displayVRButton();
  77212. }
  77213. else {
  77214. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  77215. if (e.vrDisplay) {
  77216. _this.displayVRButton();
  77217. }
  77218. });
  77219. }
  77220. // Exiting VR mode using 'ESC' key on desktop
  77221. this._onKeyDown = function (event) {
  77222. if (event.keyCode === 27 && _this.isInVRMode) {
  77223. _this.exitVR();
  77224. }
  77225. };
  77226. document.addEventListener("keydown", this._onKeyDown);
  77227. // Exiting VR mode double tapping the touch screen
  77228. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  77229. if (_this.isInVRMode) {
  77230. _this.exitVR();
  77231. if (_this._fullscreenVRpresenting) {
  77232. _this._scene.getEngine().switchFullscreen(true);
  77233. }
  77234. }
  77235. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  77236. // Listen for WebVR display changes
  77237. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  77238. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  77239. this._onVRRequestPresentStart = function () {
  77240. _this._webVRrequesting = true;
  77241. _this.updateButtonVisibility();
  77242. };
  77243. this._onVRRequestPresentComplete = function (success) {
  77244. _this._webVRrequesting = false;
  77245. _this.updateButtonVisibility();
  77246. };
  77247. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  77248. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  77249. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  77250. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  77251. scene.onDisposeObservable.add(function () {
  77252. _this.dispose();
  77253. });
  77254. // Gamepad connection events
  77255. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  77256. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  77257. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  77258. this.updateButtonVisibility();
  77259. //create easing functions
  77260. this._circleEase = new BABYLON.CircleEase();
  77261. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  77262. }
  77263. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  77264. /** Return this.onEnteringVRObservable
  77265. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  77266. */
  77267. get: function () {
  77268. return this.onEnteringVRObservable;
  77269. },
  77270. enumerable: true,
  77271. configurable: true
  77272. });
  77273. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  77274. /** Return this.onExitingVRObservable
  77275. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  77276. */
  77277. get: function () {
  77278. return this.onExitingVRObservable;
  77279. },
  77280. enumerable: true,
  77281. configurable: true
  77282. });
  77283. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  77284. /** Return this.onControllerMeshLoadedObservable
  77285. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  77286. */
  77287. get: function () {
  77288. return this.onControllerMeshLoadedObservable;
  77289. },
  77290. enumerable: true,
  77291. configurable: true
  77292. });
  77293. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  77294. /**
  77295. * The mesh used to display where the user is going to teleport.
  77296. */
  77297. get: function () {
  77298. return this._teleportationTarget;
  77299. },
  77300. /**
  77301. * Sets the mesh to be used to display where the user is going to teleport.
  77302. */
  77303. set: function (value) {
  77304. if (value) {
  77305. value.name = "teleportationTarget";
  77306. this._isDefaultTeleportationTarget = false;
  77307. this._teleportationTarget = value;
  77308. }
  77309. },
  77310. enumerable: true,
  77311. configurable: true
  77312. });
  77313. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  77314. /**
  77315. * If the ray of the gaze should be displayed.
  77316. */
  77317. get: function () {
  77318. return this._displayGaze;
  77319. },
  77320. /**
  77321. * Sets if the ray of the gaze should be displayed.
  77322. */
  77323. set: function (value) {
  77324. this._displayGaze = value;
  77325. if (!value) {
  77326. this._gazeTracker.isVisible = false;
  77327. }
  77328. },
  77329. enumerable: true,
  77330. configurable: true
  77331. });
  77332. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  77333. /**
  77334. * If the ray of the LaserPointer should be displayed.
  77335. */
  77336. get: function () {
  77337. return this._displayLaserPointer;
  77338. },
  77339. /**
  77340. * Sets if the ray of the LaserPointer should be displayed.
  77341. */
  77342. set: function (value) {
  77343. this._displayLaserPointer = value;
  77344. if (!value) {
  77345. if (this._rightLaserPointer) {
  77346. this._rightLaserPointer.isVisible = false;
  77347. }
  77348. if (this._leftLaserPointer) {
  77349. this._leftLaserPointer.isVisible = false;
  77350. }
  77351. }
  77352. else {
  77353. if (this._rightLaserPointer) {
  77354. this._rightLaserPointer.isVisible = true;
  77355. }
  77356. else if (this._leftLaserPointer) {
  77357. this._leftLaserPointer.isVisible = true;
  77358. }
  77359. }
  77360. },
  77361. enumerable: true,
  77362. configurable: true
  77363. });
  77364. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  77365. /**
  77366. * The deviceOrientationCamera used as the camera when not in VR.
  77367. */
  77368. get: function () {
  77369. return this._deviceOrientationCamera;
  77370. },
  77371. enumerable: true,
  77372. configurable: true
  77373. });
  77374. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  77375. /**
  77376. * Based on the current WebVR support, returns the current VR camera used.
  77377. */
  77378. get: function () {
  77379. if (this._webVRready) {
  77380. return this._webVRCamera;
  77381. }
  77382. else {
  77383. return this._scene.activeCamera;
  77384. }
  77385. },
  77386. enumerable: true,
  77387. configurable: true
  77388. });
  77389. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  77390. /**
  77391. * The webVRCamera which is used when in VR.
  77392. */
  77393. get: function () {
  77394. return this._webVRCamera;
  77395. },
  77396. enumerable: true,
  77397. configurable: true
  77398. });
  77399. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  77400. /**
  77401. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  77402. */
  77403. get: function () {
  77404. return this._vrDeviceOrientationCamera;
  77405. },
  77406. enumerable: true,
  77407. configurable: true
  77408. });
  77409. // Raised when one of the controller has loaded successfully its associated default mesh
  77410. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  77411. this._tryEnableInteractionOnController(webVRController);
  77412. try {
  77413. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  77414. }
  77415. catch (err) {
  77416. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  77417. }
  77418. };
  77419. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  77420. /**
  77421. * Gets a value indicating if we are currently in VR mode.
  77422. */
  77423. get: function () {
  77424. return this._webVRpresenting || this._fullscreenVRpresenting;
  77425. },
  77426. enumerable: true,
  77427. configurable: true
  77428. });
  77429. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  77430. var vrDisplay = this._scene.getEngine().getVRDevice();
  77431. if (vrDisplay) {
  77432. var wasPresenting = this._webVRpresenting;
  77433. // A VR display is connected
  77434. this._webVRpresenting = vrDisplay.isPresenting;
  77435. if (wasPresenting && !this._webVRpresenting)
  77436. this.exitVR();
  77437. }
  77438. else {
  77439. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  77440. }
  77441. this.updateButtonVisibility();
  77442. };
  77443. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  77444. this._webVRsupported = eventArgs.vrSupported;
  77445. this._webVRready = !!eventArgs.vrDisplay;
  77446. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  77447. this.updateButtonVisibility();
  77448. };
  77449. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  77450. if (this._canvas && !this._useCustomVRButton) {
  77451. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  77452. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  77453. }
  77454. };
  77455. VRExperienceHelper.prototype.displayVRButton = function () {
  77456. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  77457. document.body.appendChild(this._btnVR);
  77458. this._btnVRDisplayed = true;
  77459. }
  77460. };
  77461. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  77462. if (!this._btnVR || this._useCustomVRButton) {
  77463. return;
  77464. }
  77465. this._btnVR.className = "babylonVRicon";
  77466. if (this.isInVRMode) {
  77467. this._btnVR.className += " vrdisplaypresenting";
  77468. }
  77469. else {
  77470. if (this._webVRready)
  77471. this._btnVR.className += " vrdisplayready";
  77472. if (this._webVRsupported)
  77473. this._btnVR.className += " vrdisplaysupported";
  77474. if (this._webVRrequesting)
  77475. this._btnVR.className += " vrdisplayrequesting";
  77476. }
  77477. };
  77478. /**
  77479. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  77480. * Otherwise, will use the fullscreen API.
  77481. */
  77482. VRExperienceHelper.prototype.enterVR = function () {
  77483. if (this.onEnteringVRObservable) {
  77484. try {
  77485. this.onEnteringVRObservable.notifyObservers(this);
  77486. }
  77487. catch (err) {
  77488. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  77489. }
  77490. }
  77491. if (this._scene.activeCamera) {
  77492. this._position = this._scene.activeCamera.position.clone();
  77493. // make sure that we return to the last active camera
  77494. this._existingCamera = this._scene.activeCamera;
  77495. }
  77496. if (this._webVRrequesting)
  77497. return;
  77498. // If WebVR is supported and a headset is connected
  77499. if (this._webVRready) {
  77500. if (!this._webVRpresenting) {
  77501. this._webVRCamera.position = this._position;
  77502. this._scene.activeCamera = this._webVRCamera;
  77503. }
  77504. }
  77505. else if (this._vrDeviceOrientationCamera) {
  77506. this._vrDeviceOrientationCamera.position = this._position;
  77507. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  77508. this._scene.getEngine().switchFullscreen(true);
  77509. this.updateButtonVisibility();
  77510. }
  77511. if (this._scene.activeCamera && this._canvas) {
  77512. this._scene.activeCamera.attachControl(this._canvas);
  77513. }
  77514. if (this._interactionsEnabled) {
  77515. this._scene.registerBeforeRender(this.beforeRender);
  77516. }
  77517. };
  77518. /**
  77519. * Attempt to exit VR, or fullscreen.
  77520. */
  77521. VRExperienceHelper.prototype.exitVR = function () {
  77522. if (this.onExitingVRObservable) {
  77523. try {
  77524. this.onExitingVRObservable.notifyObservers(this);
  77525. }
  77526. catch (err) {
  77527. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  77528. }
  77529. }
  77530. if (this._webVRpresenting) {
  77531. this._scene.getEngine().disableVR();
  77532. }
  77533. if (this._scene.activeCamera) {
  77534. this._position = this._scene.activeCamera.position.clone();
  77535. }
  77536. if (this._deviceOrientationCamera) {
  77537. this._deviceOrientationCamera.position = this._position;
  77538. this._scene.activeCamera = this._deviceOrientationCamera;
  77539. if (this._canvas) {
  77540. this._scene.activeCamera.attachControl(this._canvas);
  77541. }
  77542. }
  77543. else if (this._existingCamera) {
  77544. this._existingCamera.position = this._position;
  77545. this._scene.activeCamera = this._existingCamera;
  77546. }
  77547. this.updateButtonVisibility();
  77548. if (this._interactionsEnabled) {
  77549. this._scene.unregisterBeforeRender(this.beforeRender);
  77550. }
  77551. };
  77552. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  77553. /**
  77554. * The position of the vr experience helper.
  77555. */
  77556. get: function () {
  77557. return this._position;
  77558. },
  77559. /**
  77560. * Sets the position of the vr experience helper.
  77561. */
  77562. set: function (value) {
  77563. this._position = value;
  77564. if (this._scene.activeCamera) {
  77565. this._scene.activeCamera.position = value;
  77566. }
  77567. },
  77568. enumerable: true,
  77569. configurable: true
  77570. });
  77571. /**
  77572. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  77573. */
  77574. VRExperienceHelper.prototype.enableInteractions = function () {
  77575. var _this = this;
  77576. if (!this._interactionsEnabled) {
  77577. this._interactionsRequested = true;
  77578. if (this._leftControllerReady && this._webVRCamera.leftController) {
  77579. this._enableInteractionOnController(this._webVRCamera.leftController);
  77580. }
  77581. if (this._rightControllerReady && this._webVRCamera.rightController) {
  77582. this._enableInteractionOnController(this._webVRCamera.rightController);
  77583. }
  77584. this._createGazeTracker();
  77585. this.raySelectionPredicate = function (mesh) {
  77586. return mesh.isVisible;
  77587. };
  77588. this.meshSelectionPredicate = function (mesh) {
  77589. return true;
  77590. };
  77591. this._raySelectionPredicate = function (mesh) {
  77592. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  77593. && mesh.name.indexOf("teleportationTarget") === -1
  77594. && mesh.name.indexOf("torusTeleportation") === -1
  77595. && mesh.name.indexOf("laserPointer") === -1)) {
  77596. return _this.raySelectionPredicate(mesh);
  77597. }
  77598. return false;
  77599. };
  77600. this._interactionsEnabled = true;
  77601. }
  77602. };
  77603. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  77604. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  77605. if (this._floorMeshesCollection[i].id === mesh.id) {
  77606. return true;
  77607. }
  77608. }
  77609. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  77610. return true;
  77611. }
  77612. return false;
  77613. };
  77614. /**
  77615. * Adds a floor mesh to be used for teleportation.
  77616. * @param floorMesh the mesh to be used for teleportation.
  77617. */
  77618. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  77619. if (!this._floorMeshesCollection) {
  77620. return;
  77621. }
  77622. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  77623. return;
  77624. }
  77625. this._floorMeshesCollection.push(floorMesh);
  77626. };
  77627. /**
  77628. * Removes a floor mesh from being used for teleportation.
  77629. * @param floorMesh the mesh to be removed.
  77630. */
  77631. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  77632. if (!this._floorMeshesCollection) {
  77633. return;
  77634. }
  77635. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  77636. if (meshIndex !== -1) {
  77637. this._floorMeshesCollection.splice(meshIndex, 1);
  77638. }
  77639. };
  77640. /**
  77641. * Enables interactions and teleportation using the VR controllers and gaze.
  77642. * @param vrTeleportationOptions options to modify teleportation behavior.
  77643. */
  77644. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  77645. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  77646. if (!this._teleportationInitialized) {
  77647. this._teleportationRequested = true;
  77648. this.enableInteractions();
  77649. if (vrTeleportationOptions.floorMeshName) {
  77650. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  77651. }
  77652. if (vrTeleportationOptions.floorMeshes) {
  77653. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  77654. }
  77655. if (this._leftControllerReady && this._webVRCamera.leftController) {
  77656. this._enableTeleportationOnController(this._webVRCamera.leftController);
  77657. }
  77658. if (this._rightControllerReady && this._webVRCamera.rightController) {
  77659. this._enableTeleportationOnController(this._webVRCamera.rightController);
  77660. }
  77661. // Creates an image processing post process for the vignette not relying
  77662. // on the main scene configuration for image processing to reduce setup and spaces
  77663. // (gamma/linear) conflicts.
  77664. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  77665. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77666. imageProcessingConfiguration.vignetteEnabled = true;
  77667. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  77668. this._webVRCamera.detachPostProcess(this._postProcessMove);
  77669. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  77670. this._teleportationInitialized = true;
  77671. if (this._isDefaultTeleportationTarget) {
  77672. this._createTeleportationCircles();
  77673. }
  77674. }
  77675. };
  77676. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  77677. var _this = this;
  77678. var controllerMesh = webVRController.mesh;
  77679. if (controllerMesh) {
  77680. var makeNotPick = function (root) {
  77681. root.name += " laserPointer";
  77682. root.getChildMeshes().forEach(function (c) {
  77683. makeNotPick(c);
  77684. });
  77685. };
  77686. makeNotPick(controllerMesh);
  77687. var childMeshes = controllerMesh.getChildMeshes();
  77688. for (var i = 0; i < childMeshes.length; i++) {
  77689. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  77690. controllerMesh = childMeshes[i];
  77691. break;
  77692. }
  77693. }
  77694. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  77695. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  77696. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77697. laserPointerMaterial.alpha = 0.6;
  77698. laserPointer.material = laserPointerMaterial;
  77699. laserPointer.rotation.x = Math.PI / 2;
  77700. laserPointer.parent = controllerMesh;
  77701. laserPointer.position.z = -0.5;
  77702. laserPointer.isVisible = false;
  77703. if (webVRController.hand === "left") {
  77704. this._leftLaserPointer = laserPointer;
  77705. this._interactionsEnabledOnLeftController = true;
  77706. if (!this._rightLaserPointer) {
  77707. this._leftLaserPointer.isVisible = true;
  77708. }
  77709. }
  77710. else {
  77711. this._rightLaserPointer = laserPointer;
  77712. this._interactionsEnabledOnRightController = true;
  77713. if (!this._leftLaserPointer) {
  77714. this._rightLaserPointer.isVisible = true;
  77715. }
  77716. }
  77717. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  77718. // Enabling / disabling laserPointer
  77719. if (_this._displayLaserPointer && stateObject.value === 1) {
  77720. laserPointer.isVisible = !laserPointer.isVisible;
  77721. // Laser pointer can only be active on left or right, not both at the same time
  77722. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  77723. _this._rightLaserPointer.isVisible = false;
  77724. }
  77725. else if (_this._leftLaserPointer) {
  77726. _this._leftLaserPointer.isVisible = false;
  77727. }
  77728. }
  77729. });
  77730. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  77731. if (!_this._pointerDownOnMeshAsked) {
  77732. if (stateObject.value > _this._padSensibilityUp) {
  77733. _this._selectionPointerDown();
  77734. }
  77735. }
  77736. else if (stateObject.value < _this._padSensibilityDown) {
  77737. _this._selectionPointerUp();
  77738. }
  77739. });
  77740. }
  77741. };
  77742. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  77743. if (webVRController === void 0) { webVRController = null; }
  77744. if (!this._teleportationRequestInitiated) {
  77745. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  77746. if (webVRController) {
  77747. // If laser pointer wasn't enabled yet
  77748. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  77749. this._leftLaserPointer.isVisible = true;
  77750. if (this._rightLaserPointer) {
  77751. this._rightLaserPointer.isVisible = false;
  77752. }
  77753. }
  77754. else if (this._displayLaserPointer && this._rightLaserPointer) {
  77755. this._rightLaserPointer.isVisible = true;
  77756. if (this._leftLaserPointer) {
  77757. this._leftLaserPointer.isVisible = false;
  77758. }
  77759. }
  77760. }
  77761. this._teleportationRequestInitiated = true;
  77762. }
  77763. }
  77764. else {
  77765. // Listening to the proper controller values changes to confirm teleportation
  77766. if (webVRController == null
  77767. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  77768. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  77769. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  77770. if (this._teleportationAllowed) {
  77771. this._teleportationAllowed = false;
  77772. this._teleportCamera();
  77773. }
  77774. this._teleportationRequestInitiated = false;
  77775. }
  77776. }
  77777. }
  77778. };
  77779. VRExperienceHelper.prototype._selectionPointerDown = function () {
  77780. this._pointerDownOnMeshAsked = true;
  77781. if (this._currentMeshSelected && this._currentHit) {
  77782. this._scene.simulatePointerDown(this._currentHit);
  77783. }
  77784. };
  77785. VRExperienceHelper.prototype._selectionPointerUp = function () {
  77786. if (this._currentMeshSelected && this._currentHit) {
  77787. this._scene.simulatePointerUp(this._currentHit);
  77788. }
  77789. this._pointerDownOnMeshAsked = false;
  77790. };
  77791. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  77792. // Only rotate when user is not currently selecting a teleportation location
  77793. if (this._teleportationRequestInitiated) {
  77794. return;
  77795. }
  77796. if (!this._rotationLeftAsked) {
  77797. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  77798. this._rotationLeftAsked = true;
  77799. if (this._rotationAllowed) {
  77800. this._rotateCamera(false);
  77801. }
  77802. }
  77803. }
  77804. else {
  77805. if (stateObject.x > -this._padSensibilityDown) {
  77806. this._rotationLeftAsked = false;
  77807. }
  77808. }
  77809. if (!this._rotationRightAsked) {
  77810. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  77811. this._rotationRightAsked = true;
  77812. if (this._rotationAllowed) {
  77813. this._rotateCamera(true);
  77814. }
  77815. }
  77816. }
  77817. else {
  77818. if (stateObject.x < this._padSensibilityDown) {
  77819. this._rotationRightAsked = false;
  77820. }
  77821. }
  77822. };
  77823. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  77824. // Only teleport backwards when user is not currently selecting a teleportation location
  77825. if (this._teleportationRequestInitiated) {
  77826. return;
  77827. }
  77828. // Teleport backwards
  77829. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  77830. if (!this._teleportationBackRequestInitiated) {
  77831. if (!this.currentVRCamera) {
  77832. return;
  77833. }
  77834. // Get rotation and position of the current camera
  77835. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  77836. var position = this.currentVRCamera.position;
  77837. // If the camera has device position, use that instead
  77838. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  77839. rotation = this.currentVRCamera.deviceRotationQuaternion;
  77840. position = this.currentVRCamera.devicePosition;
  77841. }
  77842. // Get matrix with only the y rotation of the device rotation
  77843. rotation.toEulerAnglesToRef(this._workingVector);
  77844. this._workingVector.z = 0;
  77845. this._workingVector.x = 0;
  77846. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  77847. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  77848. // Rotate backwards ray by device rotation to cast at the ground behind the user
  77849. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  77850. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  77851. var ray = new BABYLON.Ray(position, this._workingVector);
  77852. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  77853. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  77854. this._teleportCamera(hit.pickedPoint);
  77855. }
  77856. this._teleportationBackRequestInitiated = true;
  77857. }
  77858. }
  77859. else {
  77860. this._teleportationBackRequestInitiated = false;
  77861. }
  77862. };
  77863. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  77864. var _this = this;
  77865. var controllerMesh = webVRController.mesh;
  77866. if (controllerMesh) {
  77867. if (webVRController.hand === "left") {
  77868. if (!this._interactionsEnabledOnLeftController) {
  77869. this._enableInteractionOnController(webVRController);
  77870. }
  77871. this._teleportationEnabledOnLeftController = true;
  77872. }
  77873. else {
  77874. if (!this._interactionsEnabledOnRightController) {
  77875. this._enableInteractionOnController(webVRController);
  77876. }
  77877. this._teleportationEnabledOnRightController = true;
  77878. }
  77879. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  77880. this._dpadPressed = false;
  77881. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  77882. _this._dpadPressed = stateObject.pressed;
  77883. if (!_this._dpadPressed) {
  77884. _this._rotationLeftAsked = false;
  77885. _this._rotationRightAsked = false;
  77886. _this._teleportationBackRequestInitiated = false;
  77887. }
  77888. });
  77889. }
  77890. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  77891. if (_this.teleportationEnabled) {
  77892. _this._checkTeleportBackwards(stateObject);
  77893. _this._checkTeleportWithRay(stateObject, webVRController);
  77894. }
  77895. _this._checkRotate(stateObject);
  77896. });
  77897. }
  77898. };
  77899. // Gaze support used to point to teleport or to interact with an object
  77900. VRExperienceHelper.prototype._createGazeTracker = function () {
  77901. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  77902. this._gazeTracker.bakeCurrentTransformIntoVertices();
  77903. this._gazeTracker.isPickable = false;
  77904. this._gazeTracker.isVisible = false;
  77905. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  77906. targetMat.specularColor = BABYLON.Color3.Black();
  77907. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77908. targetMat.backFaceCulling = false;
  77909. this._gazeTracker.material = targetMat;
  77910. };
  77911. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  77912. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  77913. this._teleportationTarget.isPickable = false;
  77914. var length = 512;
  77915. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  77916. dynamicTexture.hasAlpha = true;
  77917. var context = dynamicTexture.getContext();
  77918. var centerX = length / 2;
  77919. var centerY = length / 2;
  77920. var radius = 200;
  77921. context.beginPath();
  77922. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  77923. context.fillStyle = this._teleportationFillColor;
  77924. context.fill();
  77925. context.lineWidth = 10;
  77926. context.strokeStyle = this._teleportationBorderColor;
  77927. context.stroke();
  77928. context.closePath();
  77929. dynamicTexture.update();
  77930. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  77931. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  77932. this._teleportationTarget.material = teleportationCircleMaterial;
  77933. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  77934. torus.isPickable = false;
  77935. torus.parent = this._teleportationTarget;
  77936. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  77937. var keys = [];
  77938. keys.push({
  77939. frame: 0,
  77940. value: 0
  77941. });
  77942. keys.push({
  77943. frame: 30,
  77944. value: 0.4
  77945. });
  77946. keys.push({
  77947. frame: 60,
  77948. value: 0
  77949. });
  77950. animationInnerCircle.setKeys(keys);
  77951. var easingFunction = new BABYLON.SineEase();
  77952. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  77953. animationInnerCircle.setEasingFunction(easingFunction);
  77954. torus.animations = [];
  77955. torus.animations.push(animationInnerCircle);
  77956. this._scene.beginAnimation(torus, 0, 60, true);
  77957. this._hideTeleportationTarget();
  77958. };
  77959. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  77960. if (this._teleportationInitialized) {
  77961. this._teleportationTarget.isVisible = true;
  77962. if (this._isDefaultTeleportationTarget) {
  77963. this._teleportationTarget.getChildren()[0].isVisible = true;
  77964. }
  77965. }
  77966. };
  77967. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  77968. if (this._teleportationInitialized) {
  77969. this._teleportationTarget.isVisible = false;
  77970. if (this._isDefaultTeleportationTarget) {
  77971. this._teleportationTarget.getChildren()[0].isVisible = false;
  77972. }
  77973. }
  77974. };
  77975. VRExperienceHelper.prototype._rotateCamera = function (right) {
  77976. var _this = this;
  77977. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77978. return;
  77979. }
  77980. if (right) {
  77981. this._rotationAngle++;
  77982. }
  77983. else {
  77984. this._rotationAngle--;
  77985. }
  77986. this.currentVRCamera.animations = [];
  77987. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  77988. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77989. var animationRotationKeys = [];
  77990. animationRotationKeys.push({
  77991. frame: 0,
  77992. value: this.currentVRCamera.rotationQuaternion
  77993. });
  77994. animationRotationKeys.push({
  77995. frame: 6,
  77996. value: target
  77997. });
  77998. animationRotation.setKeys(animationRotationKeys);
  77999. animationRotation.setEasingFunction(this._circleEase);
  78000. this.currentVRCamera.animations.push(animationRotation);
  78001. this._postProcessMove.animations = [];
  78002. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  78003. var vignetteWeightKeys = [];
  78004. vignetteWeightKeys.push({
  78005. frame: 0,
  78006. value: 0
  78007. });
  78008. vignetteWeightKeys.push({
  78009. frame: 3,
  78010. value: 4
  78011. });
  78012. vignetteWeightKeys.push({
  78013. frame: 6,
  78014. value: 0
  78015. });
  78016. animationPP.setKeys(vignetteWeightKeys);
  78017. animationPP.setEasingFunction(this._circleEase);
  78018. this._postProcessMove.animations.push(animationPP);
  78019. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  78020. var vignetteStretchKeys = [];
  78021. vignetteStretchKeys.push({
  78022. frame: 0,
  78023. value: 0
  78024. });
  78025. vignetteStretchKeys.push({
  78026. frame: 3,
  78027. value: 10
  78028. });
  78029. vignetteStretchKeys.push({
  78030. frame: 6,
  78031. value: 0
  78032. });
  78033. animationPP2.setKeys(vignetteStretchKeys);
  78034. animationPP2.setEasingFunction(this._circleEase);
  78035. this._postProcessMove.animations.push(animationPP2);
  78036. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  78037. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  78038. this._webVRCamera.attachPostProcess(this._postProcessMove);
  78039. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  78040. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  78041. });
  78042. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  78043. };
  78044. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  78045. if (hit.pickedPoint) {
  78046. this._teleportationAllowed = true;
  78047. if (this._teleportationRequestInitiated) {
  78048. this._displayTeleportationTarget();
  78049. }
  78050. else {
  78051. this._hideTeleportationTarget();
  78052. }
  78053. this._haloCenter.copyFrom(hit.pickedPoint);
  78054. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  78055. var pickNormal = hit.getNormal(true, false);
  78056. if (pickNormal) {
  78057. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  78058. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  78059. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  78060. }
  78061. this._teleportationTarget.position.y += 0.1;
  78062. }
  78063. };
  78064. VRExperienceHelper.prototype._teleportCamera = function (location) {
  78065. var _this = this;
  78066. if (location === void 0) { location = null; }
  78067. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  78068. return;
  78069. }
  78070. if (!location) {
  78071. location = this._haloCenter;
  78072. }
  78073. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  78074. // offset of the headset from the anchor.
  78075. if (this.webVRCamera.leftCamera) {
  78076. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  78077. this._workingVector.subtractInPlace(this.webVRCamera.position);
  78078. location.subtractToRef(this._workingVector, this._workingVector);
  78079. }
  78080. else {
  78081. this._workingVector.copyFrom(location);
  78082. }
  78083. // Add height to account for user's height offset
  78084. if (this.isInVRMode) {
  78085. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  78086. }
  78087. else {
  78088. this._workingVector.y += this._defaultHeight;
  78089. }
  78090. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  78091. // Create animation from the camera's position to the new location
  78092. this.currentVRCamera.animations = [];
  78093. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  78094. var animationCameraTeleportationKeys = [{
  78095. frame: 0,
  78096. value: this.currentVRCamera.position
  78097. },
  78098. {
  78099. frame: 11,
  78100. value: this._workingVector
  78101. }
  78102. ];
  78103. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  78104. animationCameraTeleportation.setEasingFunction(this._circleEase);
  78105. this.currentVRCamera.animations.push(animationCameraTeleportation);
  78106. this._postProcessMove.animations = [];
  78107. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  78108. var vignetteWeightKeys = [];
  78109. vignetteWeightKeys.push({
  78110. frame: 0,
  78111. value: 0
  78112. });
  78113. vignetteWeightKeys.push({
  78114. frame: 5,
  78115. value: 8
  78116. });
  78117. vignetteWeightKeys.push({
  78118. frame: 11,
  78119. value: 0
  78120. });
  78121. animationPP.setKeys(vignetteWeightKeys);
  78122. this._postProcessMove.animations.push(animationPP);
  78123. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  78124. var vignetteStretchKeys = [];
  78125. vignetteStretchKeys.push({
  78126. frame: 0,
  78127. value: 0
  78128. });
  78129. vignetteStretchKeys.push({
  78130. frame: 5,
  78131. value: 10
  78132. });
  78133. vignetteStretchKeys.push({
  78134. frame: 11,
  78135. value: 0
  78136. });
  78137. animationPP2.setKeys(vignetteStretchKeys);
  78138. this._postProcessMove.animations.push(animationPP2);
  78139. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  78140. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  78141. this._webVRCamera.attachPostProcess(this._postProcessMove);
  78142. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  78143. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  78144. });
  78145. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  78146. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  78147. });
  78148. };
  78149. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  78150. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  78151. return;
  78152. }
  78153. var ray;
  78154. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  78155. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  78156. }
  78157. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  78158. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  78159. }
  78160. else {
  78161. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  78162. }
  78163. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  78164. // Moving the gazeTracker on the mesh face targetted
  78165. if (hit && hit.pickedPoint) {
  78166. if (this._displayGaze) {
  78167. var multiplier = 1;
  78168. this._gazeTracker.isVisible = true;
  78169. if (this._isActionableMesh) {
  78170. multiplier = 3;
  78171. }
  78172. this._gazeTracker.scaling.x = hit.distance * multiplier;
  78173. this._gazeTracker.scaling.y = hit.distance * multiplier;
  78174. this._gazeTracker.scaling.z = hit.distance * multiplier;
  78175. var pickNormal = hit.getNormal();
  78176. // To avoid z-fighting
  78177. var deltaFighting = 0.002;
  78178. if (pickNormal) {
  78179. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  78180. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  78181. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  78182. }
  78183. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  78184. if (this._gazeTracker.position.x < 0) {
  78185. this._gazeTracker.position.x += deltaFighting;
  78186. }
  78187. else {
  78188. this._gazeTracker.position.x -= deltaFighting;
  78189. }
  78190. if (this._gazeTracker.position.y < 0) {
  78191. this._gazeTracker.position.y += deltaFighting;
  78192. }
  78193. else {
  78194. this._gazeTracker.position.y -= deltaFighting;
  78195. }
  78196. if (this._gazeTracker.position.z < 0) {
  78197. this._gazeTracker.position.z += deltaFighting;
  78198. }
  78199. else {
  78200. this._gazeTracker.position.z -= deltaFighting;
  78201. }
  78202. }
  78203. // Changing the size of the laser pointer based on the distance from the targetted point
  78204. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  78205. this._rightLaserPointer.scaling.y = hit.distance;
  78206. this._rightLaserPointer.position.z = -hit.distance / 2;
  78207. }
  78208. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  78209. this._leftLaserPointer.scaling.y = hit.distance;
  78210. this._leftLaserPointer.position.z = -hit.distance / 2;
  78211. }
  78212. }
  78213. else {
  78214. this._gazeTracker.isVisible = false;
  78215. }
  78216. if (hit && hit.pickedMesh) {
  78217. this._currentHit = hit;
  78218. if (this._pointerDownOnMeshAsked) {
  78219. this._scene.simulatePointerMove(this._currentHit);
  78220. }
  78221. // The object selected is the floor, we're in a teleportation scenario
  78222. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  78223. // Moving the teleportation area to this targetted point
  78224. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  78225. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  78226. this._notifySelectedMeshUnselected();
  78227. }
  78228. this._currentMeshSelected = null;
  78229. this._moveTeleportationSelectorTo(hit);
  78230. return;
  78231. }
  78232. // If not, we're in a selection scenario
  78233. this._hideTeleportationTarget();
  78234. this._teleportationAllowed = false;
  78235. if (hit.pickedMesh !== this._currentMeshSelected) {
  78236. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  78237. this.onNewMeshPicked.notifyObservers(hit);
  78238. this._currentMeshSelected = hit.pickedMesh;
  78239. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  78240. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  78241. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  78242. this._isActionableMesh = true;
  78243. }
  78244. else {
  78245. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78246. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78247. this._isActionableMesh = false;
  78248. }
  78249. try {
  78250. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  78251. }
  78252. catch (err) {
  78253. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  78254. }
  78255. }
  78256. else {
  78257. this._notifySelectedMeshUnselected();
  78258. this._currentMeshSelected = null;
  78259. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78260. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78261. }
  78262. }
  78263. }
  78264. else {
  78265. this._currentHit = null;
  78266. this._notifySelectedMeshUnselected();
  78267. this._currentMeshSelected = null;
  78268. this._teleportationAllowed = false;
  78269. this._hideTeleportationTarget();
  78270. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78271. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  78272. }
  78273. };
  78274. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  78275. if (this._currentMeshSelected) {
  78276. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  78277. }
  78278. };
  78279. /**
  78280. * Sets the color of the laser ray from the vr controllers.
  78281. * @param color new color for the ray.
  78282. */
  78283. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  78284. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  78285. this._leftLaserPointer.material.emissiveColor = color;
  78286. }
  78287. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  78288. this._rightLaserPointer.material.emissiveColor = color;
  78289. }
  78290. };
  78291. /**
  78292. * Sets the color of the ray from the vr headsets gaze.
  78293. * @param color new color for the ray.
  78294. */
  78295. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  78296. if (this._gazeTracker.material) {
  78297. this._gazeTracker.material.emissiveColor = color;
  78298. }
  78299. };
  78300. /**
  78301. * Exits VR and disposes of the vr experience helper
  78302. */
  78303. VRExperienceHelper.prototype.dispose = function () {
  78304. if (this.isInVRMode) {
  78305. this.exitVR();
  78306. }
  78307. if (this._passProcessMove) {
  78308. this._passProcessMove.dispose();
  78309. }
  78310. if (this._postProcessMove) {
  78311. this._postProcessMove.dispose();
  78312. }
  78313. if (this._webVRCamera) {
  78314. this._webVRCamera.dispose();
  78315. }
  78316. if (this._vrDeviceOrientationCamera) {
  78317. this._vrDeviceOrientationCamera.dispose();
  78318. }
  78319. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  78320. document.body.removeChild(this._btnVR);
  78321. }
  78322. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  78323. this._deviceOrientationCamera.dispose();
  78324. }
  78325. if (this._gazeTracker) {
  78326. this._gazeTracker.dispose();
  78327. }
  78328. if (this._teleportationTarget) {
  78329. this._teleportationTarget.dispose();
  78330. }
  78331. this._floorMeshesCollection = [];
  78332. document.removeEventListener("keydown", this._onKeyDown);
  78333. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78334. window.removeEventListener("resize", this._onResize);
  78335. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  78336. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  78337. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  78338. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  78339. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  78340. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  78341. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  78342. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78343. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  78344. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  78345. this._scene.unregisterBeforeRender(this.beforeRender);
  78346. };
  78347. /**
  78348. * Gets the name of the VRExperienceHelper class
  78349. * @returns "VRExperienceHelper"
  78350. */
  78351. VRExperienceHelper.prototype.getClassName = function () {
  78352. return "VRExperienceHelper";
  78353. };
  78354. return VRExperienceHelper;
  78355. }());
  78356. BABYLON.VRExperienceHelper = VRExperienceHelper;
  78357. })(BABYLON || (BABYLON = {}));
  78358. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  78359. // Mainly based on these 2 articles :
  78360. // 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
  78361. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  78362. var BABYLON;
  78363. (function (BABYLON) {
  78364. var JoystickAxis;
  78365. (function (JoystickAxis) {
  78366. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  78367. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  78368. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  78369. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  78370. var VirtualJoystick = /** @class */ (function () {
  78371. function VirtualJoystick(leftJoystick) {
  78372. var _this = this;
  78373. if (leftJoystick) {
  78374. this._leftJoystick = true;
  78375. }
  78376. else {
  78377. this._leftJoystick = false;
  78378. }
  78379. VirtualJoystick._globalJoystickIndex++;
  78380. // By default left & right arrow keys are moving the X
  78381. // and up & down keys are moving the Y
  78382. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  78383. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  78384. this.reverseLeftRight = false;
  78385. this.reverseUpDown = false;
  78386. // collections of pointers
  78387. this._touches = new BABYLON.StringDictionary();
  78388. this.deltaPosition = BABYLON.Vector3.Zero();
  78389. this._joystickSensibility = 25;
  78390. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  78391. this._onResize = function (evt) {
  78392. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  78393. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  78394. if (VirtualJoystick.vjCanvas) {
  78395. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  78396. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  78397. }
  78398. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  78399. };
  78400. // injecting a canvas element on top of the canvas 3D game
  78401. if (!VirtualJoystick.vjCanvas) {
  78402. window.addEventListener("resize", this._onResize, false);
  78403. VirtualJoystick.vjCanvas = document.createElement("canvas");
  78404. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  78405. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  78406. VirtualJoystick.vjCanvas.width = window.innerWidth;
  78407. VirtualJoystick.vjCanvas.height = window.innerHeight;
  78408. VirtualJoystick.vjCanvas.style.width = "100%";
  78409. VirtualJoystick.vjCanvas.style.height = "100%";
  78410. VirtualJoystick.vjCanvas.style.position = "absolute";
  78411. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  78412. VirtualJoystick.vjCanvas.style.top = "0px";
  78413. VirtualJoystick.vjCanvas.style.left = "0px";
  78414. VirtualJoystick.vjCanvas.style.zIndex = "5";
  78415. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  78416. // Support for jQuery PEP polyfill
  78417. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  78418. var context = VirtualJoystick.vjCanvas.getContext('2d');
  78419. if (!context) {
  78420. throw new Error("Unable to create canvas for virtual joystick");
  78421. }
  78422. VirtualJoystick.vjCanvasContext = context;
  78423. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  78424. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  78425. document.body.appendChild(VirtualJoystick.vjCanvas);
  78426. }
  78427. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  78428. this.pressed = false;
  78429. // default joystick color
  78430. this._joystickColor = "cyan";
  78431. this._joystickPointerID = -1;
  78432. // current joystick position
  78433. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  78434. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  78435. // origin joystick position
  78436. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  78437. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  78438. this._onPointerDownHandlerRef = function (evt) {
  78439. _this._onPointerDown(evt);
  78440. };
  78441. this._onPointerMoveHandlerRef = function (evt) {
  78442. _this._onPointerMove(evt);
  78443. };
  78444. this._onPointerUpHandlerRef = function (evt) {
  78445. _this._onPointerUp(evt);
  78446. };
  78447. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  78448. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  78449. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  78450. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  78451. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  78452. evt.preventDefault(); // Disables system menu
  78453. }, false);
  78454. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  78455. }
  78456. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  78457. this._joystickSensibility = newJoystickSensibility;
  78458. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  78459. };
  78460. VirtualJoystick.prototype._onPointerDown = function (e) {
  78461. var positionOnScreenCondition;
  78462. e.preventDefault();
  78463. if (this._leftJoystick === true) {
  78464. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  78465. }
  78466. else {
  78467. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  78468. }
  78469. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  78470. // First contact will be dedicated to the virtual joystick
  78471. this._joystickPointerID = e.pointerId;
  78472. this._joystickPointerStartPos.x = e.clientX;
  78473. this._joystickPointerStartPos.y = e.clientY;
  78474. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  78475. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  78476. this._deltaJoystickVector.x = 0;
  78477. this._deltaJoystickVector.y = 0;
  78478. this.pressed = true;
  78479. this._touches.add(e.pointerId.toString(), e);
  78480. }
  78481. else {
  78482. // You can only trigger the action buttons with a joystick declared
  78483. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  78484. this._action();
  78485. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  78486. }
  78487. }
  78488. };
  78489. VirtualJoystick.prototype._onPointerMove = function (e) {
  78490. // If the current pointer is the one associated to the joystick (first touch contact)
  78491. if (this._joystickPointerID == e.pointerId) {
  78492. this._joystickPointerPos.x = e.clientX;
  78493. this._joystickPointerPos.y = e.clientY;
  78494. this._deltaJoystickVector = this._joystickPointerPos.clone();
  78495. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  78496. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  78497. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  78498. switch (this._axisTargetedByLeftAndRight) {
  78499. case JoystickAxis.X:
  78500. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  78501. break;
  78502. case JoystickAxis.Y:
  78503. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  78504. break;
  78505. case JoystickAxis.Z:
  78506. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  78507. break;
  78508. }
  78509. var directionUpDown = this.reverseUpDown ? 1 : -1;
  78510. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  78511. switch (this._axisTargetedByUpAndDown) {
  78512. case JoystickAxis.X:
  78513. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  78514. break;
  78515. case JoystickAxis.Y:
  78516. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  78517. break;
  78518. case JoystickAxis.Z:
  78519. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  78520. break;
  78521. }
  78522. }
  78523. else {
  78524. var data = this._touches.get(e.pointerId.toString());
  78525. if (data) {
  78526. data.x = e.clientX;
  78527. data.y = e.clientY;
  78528. }
  78529. }
  78530. };
  78531. VirtualJoystick.prototype._onPointerUp = function (e) {
  78532. if (this._joystickPointerID == e.pointerId) {
  78533. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  78534. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  78535. this._joystickPointerID = -1;
  78536. this.pressed = false;
  78537. }
  78538. else {
  78539. var touch = this._touches.get(e.pointerId.toString());
  78540. if (touch) {
  78541. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  78542. }
  78543. }
  78544. this._deltaJoystickVector.x = 0;
  78545. this._deltaJoystickVector.y = 0;
  78546. this._touches.remove(e.pointerId.toString());
  78547. };
  78548. /**
  78549. * Change the color of the virtual joystick
  78550. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  78551. */
  78552. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  78553. this._joystickColor = newColor;
  78554. };
  78555. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  78556. this._action = action;
  78557. };
  78558. // Define which axis you'd like to control for left & right
  78559. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  78560. switch (axis) {
  78561. case JoystickAxis.X:
  78562. case JoystickAxis.Y:
  78563. case JoystickAxis.Z:
  78564. this._axisTargetedByLeftAndRight = axis;
  78565. break;
  78566. default:
  78567. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  78568. break;
  78569. }
  78570. };
  78571. // Define which axis you'd like to control for up & down
  78572. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  78573. switch (axis) {
  78574. case JoystickAxis.X:
  78575. case JoystickAxis.Y:
  78576. case JoystickAxis.Z:
  78577. this._axisTargetedByUpAndDown = axis;
  78578. break;
  78579. default:
  78580. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  78581. break;
  78582. }
  78583. };
  78584. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  78585. var _this = this;
  78586. if (this.pressed) {
  78587. this._touches.forEach(function (key, touch) {
  78588. if (touch.pointerId === _this._joystickPointerID) {
  78589. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  78590. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  78591. VirtualJoystick.vjCanvasContext.beginPath();
  78592. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  78593. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  78594. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  78595. VirtualJoystick.vjCanvasContext.stroke();
  78596. VirtualJoystick.vjCanvasContext.closePath();
  78597. VirtualJoystick.vjCanvasContext.beginPath();
  78598. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  78599. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  78600. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  78601. VirtualJoystick.vjCanvasContext.stroke();
  78602. VirtualJoystick.vjCanvasContext.closePath();
  78603. VirtualJoystick.vjCanvasContext.beginPath();
  78604. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  78605. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  78606. VirtualJoystick.vjCanvasContext.stroke();
  78607. VirtualJoystick.vjCanvasContext.closePath();
  78608. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  78609. }
  78610. else {
  78611. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  78612. VirtualJoystick.vjCanvasContext.beginPath();
  78613. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  78614. VirtualJoystick.vjCanvasContext.beginPath();
  78615. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  78616. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  78617. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  78618. VirtualJoystick.vjCanvasContext.stroke();
  78619. VirtualJoystick.vjCanvasContext.closePath();
  78620. touch.prevX = touch.x;
  78621. touch.prevY = touch.y;
  78622. }
  78623. ;
  78624. });
  78625. }
  78626. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  78627. };
  78628. VirtualJoystick.prototype.releaseCanvas = function () {
  78629. if (VirtualJoystick.vjCanvas) {
  78630. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  78631. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  78632. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  78633. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  78634. window.removeEventListener("resize", this._onResize);
  78635. document.body.removeChild(VirtualJoystick.vjCanvas);
  78636. VirtualJoystick.vjCanvas = null;
  78637. }
  78638. };
  78639. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  78640. VirtualJoystick._globalJoystickIndex = 0;
  78641. return VirtualJoystick;
  78642. }());
  78643. BABYLON.VirtualJoystick = VirtualJoystick;
  78644. })(BABYLON || (BABYLON = {}));
  78645. //# sourceMappingURL=babylon.virtualJoystick.js.map
  78646. var BABYLON;
  78647. (function (BABYLON) {
  78648. // We're mainly based on the logic defined into the FreeCamera code
  78649. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  78650. __extends(VirtualJoysticksCamera, _super);
  78651. function VirtualJoysticksCamera(name, position, scene) {
  78652. var _this = _super.call(this, name, position, scene) || this;
  78653. _this.inputs.addVirtualJoystick();
  78654. return _this;
  78655. }
  78656. VirtualJoysticksCamera.prototype.getClassName = function () {
  78657. return "VirtualJoysticksCamera";
  78658. };
  78659. return VirtualJoysticksCamera;
  78660. }(BABYLON.FreeCamera));
  78661. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  78662. })(BABYLON || (BABYLON = {}));
  78663. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  78664. var BABYLON;
  78665. (function (BABYLON) {
  78666. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  78667. function FreeCameraVirtualJoystickInput() {
  78668. }
  78669. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  78670. return this._leftjoystick;
  78671. };
  78672. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  78673. return this._rightjoystick;
  78674. };
  78675. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  78676. if (this._leftjoystick) {
  78677. var camera = this.camera;
  78678. var speed = camera._computeLocalCameraSpeed() * 50;
  78679. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  78680. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  78681. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  78682. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  78683. if (!this._leftjoystick.pressed) {
  78684. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  78685. }
  78686. if (!this._rightjoystick.pressed) {
  78687. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  78688. }
  78689. }
  78690. };
  78691. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  78692. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  78693. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  78694. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  78695. this._leftjoystick.setJoystickSensibility(0.15);
  78696. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  78697. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  78698. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  78699. this._rightjoystick.reverseUpDown = true;
  78700. this._rightjoystick.setJoystickSensibility(0.05);
  78701. this._rightjoystick.setJoystickColor("yellow");
  78702. };
  78703. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  78704. this._leftjoystick.releaseCanvas();
  78705. this._rightjoystick.releaseCanvas();
  78706. };
  78707. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  78708. return "FreeCameraVirtualJoystickInput";
  78709. };
  78710. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  78711. return "virtualJoystick";
  78712. };
  78713. return FreeCameraVirtualJoystickInput;
  78714. }());
  78715. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  78716. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  78717. })(BABYLON || (BABYLON = {}));
  78718. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  78719. var BABYLON;
  78720. (function (BABYLON) {
  78721. var SimplificationSettings = /** @class */ (function () {
  78722. function SimplificationSettings(quality, distance, optimizeMesh) {
  78723. this.quality = quality;
  78724. this.distance = distance;
  78725. this.optimizeMesh = optimizeMesh;
  78726. }
  78727. return SimplificationSettings;
  78728. }());
  78729. BABYLON.SimplificationSettings = SimplificationSettings;
  78730. var SimplificationQueue = /** @class */ (function () {
  78731. function SimplificationQueue() {
  78732. this.running = false;
  78733. this._simplificationArray = [];
  78734. }
  78735. SimplificationQueue.prototype.addTask = function (task) {
  78736. this._simplificationArray.push(task);
  78737. };
  78738. SimplificationQueue.prototype.executeNext = function () {
  78739. var task = this._simplificationArray.pop();
  78740. if (task) {
  78741. this.running = true;
  78742. this.runSimplification(task);
  78743. }
  78744. else {
  78745. this.running = false;
  78746. }
  78747. };
  78748. SimplificationQueue.prototype.runSimplification = function (task) {
  78749. var _this = this;
  78750. if (task.parallelProcessing) {
  78751. //parallel simplifier
  78752. task.settings.forEach(function (setting) {
  78753. var simplifier = _this.getSimplifier(task);
  78754. simplifier.simplify(setting, function (newMesh) {
  78755. task.mesh.addLODLevel(setting.distance, newMesh);
  78756. newMesh.isVisible = true;
  78757. //check if it is the last
  78758. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  78759. //all done, run the success callback.
  78760. task.successCallback();
  78761. }
  78762. _this.executeNext();
  78763. });
  78764. });
  78765. }
  78766. else {
  78767. //single simplifier.
  78768. var simplifier = this.getSimplifier(task);
  78769. var runDecimation = function (setting, callback) {
  78770. simplifier.simplify(setting, function (newMesh) {
  78771. task.mesh.addLODLevel(setting.distance, newMesh);
  78772. newMesh.isVisible = true;
  78773. //run the next quality level
  78774. callback();
  78775. });
  78776. };
  78777. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  78778. runDecimation(task.settings[loop.index], function () {
  78779. loop.executeNext();
  78780. });
  78781. }, function () {
  78782. //execution ended, run the success callback.
  78783. if (task.successCallback) {
  78784. task.successCallback();
  78785. }
  78786. _this.executeNext();
  78787. });
  78788. }
  78789. };
  78790. SimplificationQueue.prototype.getSimplifier = function (task) {
  78791. switch (task.simplificationType) {
  78792. case SimplificationType.QUADRATIC:
  78793. default:
  78794. return new QuadraticErrorSimplification(task.mesh);
  78795. }
  78796. };
  78797. return SimplificationQueue;
  78798. }());
  78799. BABYLON.SimplificationQueue = SimplificationQueue;
  78800. /**
  78801. * The implemented types of simplification.
  78802. * At the moment only Quadratic Error Decimation is implemented.
  78803. */
  78804. var SimplificationType;
  78805. (function (SimplificationType) {
  78806. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  78807. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  78808. var DecimationTriangle = /** @class */ (function () {
  78809. function DecimationTriangle(vertices) {
  78810. this.vertices = vertices;
  78811. this.error = new Array(4);
  78812. this.deleted = false;
  78813. this.isDirty = false;
  78814. this.deletePending = false;
  78815. this.borderFactor = 0;
  78816. }
  78817. return DecimationTriangle;
  78818. }());
  78819. BABYLON.DecimationTriangle = DecimationTriangle;
  78820. var DecimationVertex = /** @class */ (function () {
  78821. function DecimationVertex(position, id) {
  78822. this.position = position;
  78823. this.id = id;
  78824. this.isBorder = true;
  78825. this.q = new QuadraticMatrix();
  78826. this.triangleCount = 0;
  78827. this.triangleStart = 0;
  78828. this.originalOffsets = [];
  78829. }
  78830. DecimationVertex.prototype.updatePosition = function (newPosition) {
  78831. this.position.copyFrom(newPosition);
  78832. };
  78833. return DecimationVertex;
  78834. }());
  78835. BABYLON.DecimationVertex = DecimationVertex;
  78836. var QuadraticMatrix = /** @class */ (function () {
  78837. function QuadraticMatrix(data) {
  78838. this.data = new Array(10);
  78839. for (var i = 0; i < 10; ++i) {
  78840. if (data && data[i]) {
  78841. this.data[i] = data[i];
  78842. }
  78843. else {
  78844. this.data[i] = 0;
  78845. }
  78846. }
  78847. }
  78848. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  78849. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  78850. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  78851. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  78852. return det;
  78853. };
  78854. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  78855. for (var i = 0; i < 10; ++i) {
  78856. this.data[i] += matrix.data[i];
  78857. }
  78858. };
  78859. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  78860. for (var i = 0; i < 10; ++i) {
  78861. this.data[i] += data[i];
  78862. }
  78863. };
  78864. QuadraticMatrix.prototype.add = function (matrix) {
  78865. var m = new QuadraticMatrix();
  78866. for (var i = 0; i < 10; ++i) {
  78867. m.data[i] = this.data[i] + matrix.data[i];
  78868. }
  78869. return m;
  78870. };
  78871. QuadraticMatrix.FromData = function (a, b, c, d) {
  78872. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  78873. };
  78874. //returning an array to avoid garbage collection
  78875. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  78876. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  78877. };
  78878. return QuadraticMatrix;
  78879. }());
  78880. BABYLON.QuadraticMatrix = QuadraticMatrix;
  78881. var Reference = /** @class */ (function () {
  78882. function Reference(vertexId, triangleId) {
  78883. this.vertexId = vertexId;
  78884. this.triangleId = triangleId;
  78885. }
  78886. return Reference;
  78887. }());
  78888. BABYLON.Reference = Reference;
  78889. /**
  78890. * An implementation of the Quadratic Error simplification algorithm.
  78891. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  78892. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  78893. * @author RaananW
  78894. */
  78895. var QuadraticErrorSimplification = /** @class */ (function () {
  78896. function QuadraticErrorSimplification(_mesh) {
  78897. this._mesh = _mesh;
  78898. this.syncIterations = 5000;
  78899. this.aggressiveness = 7;
  78900. this.decimationIterations = 100;
  78901. this.boundingBoxEpsilon = BABYLON.Epsilon;
  78902. }
  78903. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  78904. var _this = this;
  78905. this.initDecimatedMesh();
  78906. //iterating through the submeshes array, one after the other.
  78907. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  78908. _this.initWithMesh(loop.index, function () {
  78909. _this.runDecimation(settings, loop.index, function () {
  78910. loop.executeNext();
  78911. });
  78912. }, settings.optimizeMesh);
  78913. }, function () {
  78914. setTimeout(function () {
  78915. successCallback(_this._reconstructedMesh);
  78916. }, 0);
  78917. });
  78918. };
  78919. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  78920. var _this = this;
  78921. var targetCount = ~~(this.triangles.length * settings.quality);
  78922. var deletedTriangles = 0;
  78923. var triangleCount = this.triangles.length;
  78924. var iterationFunction = function (iteration, callback) {
  78925. setTimeout(function () {
  78926. if (iteration % 5 === 0) {
  78927. _this.updateMesh(iteration === 0);
  78928. }
  78929. for (var i = 0; i < _this.triangles.length; ++i) {
  78930. _this.triangles[i].isDirty = false;
  78931. }
  78932. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  78933. var trianglesIterator = function (i) {
  78934. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  78935. var t = _this.triangles[tIdx];
  78936. if (!t)
  78937. return;
  78938. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  78939. return;
  78940. }
  78941. for (var j = 0; j < 3; ++j) {
  78942. if (t.error[j] < threshold) {
  78943. var deleted0 = [];
  78944. var deleted1 = [];
  78945. var v0 = t.vertices[j];
  78946. var v1 = t.vertices[(j + 1) % 3];
  78947. if (v0.isBorder || v1.isBorder)
  78948. continue;
  78949. var p = BABYLON.Vector3.Zero();
  78950. var n = BABYLON.Vector3.Zero();
  78951. var uv = BABYLON.Vector2.Zero();
  78952. var color = new BABYLON.Color4(0, 0, 0, 1);
  78953. _this.calculateError(v0, v1, p, n, uv, color);
  78954. var delTr = new Array();
  78955. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  78956. continue;
  78957. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  78958. continue;
  78959. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  78960. continue;
  78961. var uniqueArray = new Array();
  78962. delTr.forEach(function (deletedT) {
  78963. if (uniqueArray.indexOf(deletedT) === -1) {
  78964. deletedT.deletePending = true;
  78965. uniqueArray.push(deletedT);
  78966. }
  78967. });
  78968. if (uniqueArray.length % 2 !== 0) {
  78969. continue;
  78970. }
  78971. v0.q = v1.q.add(v0.q);
  78972. v0.updatePosition(p);
  78973. var tStart = _this.references.length;
  78974. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  78975. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  78976. var tCount = _this.references.length - tStart;
  78977. if (tCount <= v0.triangleCount) {
  78978. if (tCount) {
  78979. for (var c = 0; c < tCount; c++) {
  78980. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  78981. }
  78982. }
  78983. }
  78984. else {
  78985. v0.triangleStart = tStart;
  78986. }
  78987. v0.triangleCount = tCount;
  78988. break;
  78989. }
  78990. }
  78991. };
  78992. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  78993. }, 0);
  78994. };
  78995. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  78996. if (triangleCount - deletedTriangles <= targetCount)
  78997. loop.breakLoop();
  78998. else {
  78999. iterationFunction(loop.index, function () {
  79000. loop.executeNext();
  79001. });
  79002. }
  79003. }, function () {
  79004. setTimeout(function () {
  79005. //reconstruct this part of the mesh
  79006. _this.reconstructMesh(submeshIndex);
  79007. successCallback();
  79008. }, 0);
  79009. });
  79010. };
  79011. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  79012. var _this = this;
  79013. this.vertices = [];
  79014. this.triangles = [];
  79015. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  79016. var indices = this._mesh.getIndices();
  79017. var submesh = this._mesh.subMeshes[submeshIndex];
  79018. var findInVertices = function (positionToSearch) {
  79019. if (optimizeMesh) {
  79020. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  79021. if (_this.vertices[ii].position.equals(positionToSearch)) {
  79022. return _this.vertices[ii];
  79023. }
  79024. }
  79025. }
  79026. return null;
  79027. };
  79028. var vertexReferences = [];
  79029. var vertexInit = function (i) {
  79030. if (!positionData) {
  79031. return;
  79032. }
  79033. var offset = i + submesh.verticesStart;
  79034. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  79035. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  79036. vertex.originalOffsets.push(offset);
  79037. if (vertex.id === _this.vertices.length) {
  79038. _this.vertices.push(vertex);
  79039. }
  79040. vertexReferences.push(vertex.id);
  79041. };
  79042. //var totalVertices = mesh.getTotalVertices();
  79043. var totalVertices = submesh.verticesCount;
  79044. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  79045. var indicesInit = function (i) {
  79046. if (!indices) {
  79047. return;
  79048. }
  79049. var offset = (submesh.indexStart / 3) + i;
  79050. var pos = (offset * 3);
  79051. var i0 = indices[pos + 0];
  79052. var i1 = indices[pos + 1];
  79053. var i2 = indices[pos + 2];
  79054. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  79055. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  79056. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  79057. var triangle = new DecimationTriangle([v0, v1, v2]);
  79058. triangle.originalOffset = pos;
  79059. _this.triangles.push(triangle);
  79060. };
  79061. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  79062. _this.init(callback);
  79063. });
  79064. });
  79065. };
  79066. QuadraticErrorSimplification.prototype.init = function (callback) {
  79067. var _this = this;
  79068. var triangleInit1 = function (i) {
  79069. var t = _this.triangles[i];
  79070. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  79071. for (var j = 0; j < 3; j++) {
  79072. 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))));
  79073. }
  79074. };
  79075. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  79076. var triangleInit2 = function (i) {
  79077. var t = _this.triangles[i];
  79078. for (var j = 0; j < 3; ++j) {
  79079. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  79080. }
  79081. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  79082. };
  79083. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  79084. callback();
  79085. });
  79086. });
  79087. };
  79088. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  79089. var newTriangles = [];
  79090. var i;
  79091. for (i = 0; i < this.vertices.length; ++i) {
  79092. this.vertices[i].triangleCount = 0;
  79093. }
  79094. var t;
  79095. var j;
  79096. for (i = 0; i < this.triangles.length; ++i) {
  79097. if (!this.triangles[i].deleted) {
  79098. t = this.triangles[i];
  79099. for (j = 0; j < 3; ++j) {
  79100. t.vertices[j].triangleCount = 1;
  79101. }
  79102. newTriangles.push(t);
  79103. }
  79104. }
  79105. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  79106. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  79107. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  79108. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  79109. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  79110. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  79111. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  79112. var vertexCount = 0;
  79113. for (i = 0; i < this.vertices.length; ++i) {
  79114. var vertex = this.vertices[i];
  79115. vertex.id = vertexCount;
  79116. if (vertex.triangleCount) {
  79117. vertex.originalOffsets.forEach(function (originalOffset) {
  79118. if (!normalData) {
  79119. return;
  79120. }
  79121. newPositionData.push(vertex.position.x);
  79122. newPositionData.push(vertex.position.y);
  79123. newPositionData.push(vertex.position.z);
  79124. newNormalData.push(normalData[originalOffset * 3]);
  79125. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  79126. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  79127. if (uvs && uvs.length) {
  79128. newUVsData.push(uvs[(originalOffset * 2)]);
  79129. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  79130. }
  79131. else if (colorsData && colorsData.length) {
  79132. newColorsData.push(colorsData[(originalOffset * 4)]);
  79133. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  79134. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  79135. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  79136. }
  79137. ++vertexCount;
  79138. });
  79139. }
  79140. }
  79141. var startingIndex = this._reconstructedMesh.getTotalIndices();
  79142. var startingVertex = this._reconstructedMesh.getTotalVertices();
  79143. var submeshesArray = this._reconstructedMesh.subMeshes;
  79144. this._reconstructedMesh.subMeshes = [];
  79145. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  79146. var originalIndices = this._mesh.getIndices();
  79147. for (i = 0; i < newTriangles.length; ++i) {
  79148. t = newTriangles[i]; //now get the new referencing point for each vertex
  79149. [0, 1, 2].forEach(function (idx) {
  79150. var id = originalIndices[t.originalOffset + idx];
  79151. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  79152. if (offset < 0)
  79153. offset = 0;
  79154. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  79155. });
  79156. }
  79157. //overwriting the old vertex buffers and indices.
  79158. this._reconstructedMesh.setIndices(newIndicesArray);
  79159. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  79160. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  79161. if (newUVsData.length > 0)
  79162. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  79163. if (newColorsData.length > 0)
  79164. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  79165. //create submesh
  79166. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  79167. if (submeshIndex > 0) {
  79168. this._reconstructedMesh.subMeshes = [];
  79169. submeshesArray.forEach(function (submesh) {
  79170. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  79171. });
  79172. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  79173. }
  79174. };
  79175. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  79176. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  79177. this._reconstructedMesh.material = this._mesh.material;
  79178. this._reconstructedMesh.parent = this._mesh.parent;
  79179. this._reconstructedMesh.isVisible = false;
  79180. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  79181. };
  79182. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  79183. for (var i = 0; i < vertex1.triangleCount; ++i) {
  79184. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  79185. if (t.deleted)
  79186. continue;
  79187. var s = this.references[vertex1.triangleStart + i].vertexId;
  79188. var v1 = t.vertices[(s + 1) % 3];
  79189. var v2 = t.vertices[(s + 2) % 3];
  79190. if ((v1 === vertex2 || v2 === vertex2)) {
  79191. deletedArray[i] = true;
  79192. delTr.push(t);
  79193. continue;
  79194. }
  79195. var d1 = v1.position.subtract(point);
  79196. d1 = d1.normalize();
  79197. var d2 = v2.position.subtract(point);
  79198. d2 = d2.normalize();
  79199. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  79200. return true;
  79201. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  79202. deletedArray[i] = false;
  79203. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  79204. return true;
  79205. }
  79206. return false;
  79207. };
  79208. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  79209. var newDeleted = deletedTriangles;
  79210. for (var i = 0; i < vertex.triangleCount; ++i) {
  79211. var ref = this.references[vertex.triangleStart + i];
  79212. var t = this.triangles[ref.triangleId];
  79213. if (t.deleted)
  79214. continue;
  79215. if (deletedArray[i] && t.deletePending) {
  79216. t.deleted = true;
  79217. newDeleted++;
  79218. continue;
  79219. }
  79220. t.vertices[ref.vertexId] = origVertex;
  79221. t.isDirty = true;
  79222. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  79223. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  79224. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  79225. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  79226. this.references.push(ref);
  79227. }
  79228. return newDeleted;
  79229. };
  79230. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  79231. for (var i = 0; i < this.vertices.length; ++i) {
  79232. var vCount = [];
  79233. var vId = [];
  79234. var v = this.vertices[i];
  79235. var j;
  79236. for (j = 0; j < v.triangleCount; ++j) {
  79237. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  79238. for (var ii = 0; ii < 3; ii++) {
  79239. var ofs = 0;
  79240. var vv = triangle.vertices[ii];
  79241. while (ofs < vCount.length) {
  79242. if (vId[ofs] === vv.id)
  79243. break;
  79244. ++ofs;
  79245. }
  79246. if (ofs === vCount.length) {
  79247. vCount.push(1);
  79248. vId.push(vv.id);
  79249. }
  79250. else {
  79251. vCount[ofs]++;
  79252. }
  79253. }
  79254. }
  79255. for (j = 0; j < vCount.length; ++j) {
  79256. if (vCount[j] === 1) {
  79257. this.vertices[vId[j]].isBorder = true;
  79258. }
  79259. else {
  79260. this.vertices[vId[j]].isBorder = false;
  79261. }
  79262. }
  79263. }
  79264. };
  79265. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  79266. if (identifyBorders === void 0) { identifyBorders = false; }
  79267. var i;
  79268. if (!identifyBorders) {
  79269. var newTrianglesVector = [];
  79270. for (i = 0; i < this.triangles.length; ++i) {
  79271. if (!this.triangles[i].deleted) {
  79272. newTrianglesVector.push(this.triangles[i]);
  79273. }
  79274. }
  79275. this.triangles = newTrianglesVector;
  79276. }
  79277. for (i = 0; i < this.vertices.length; ++i) {
  79278. this.vertices[i].triangleCount = 0;
  79279. this.vertices[i].triangleStart = 0;
  79280. }
  79281. var t;
  79282. var j;
  79283. var v;
  79284. for (i = 0; i < this.triangles.length; ++i) {
  79285. t = this.triangles[i];
  79286. for (j = 0; j < 3; ++j) {
  79287. v = t.vertices[j];
  79288. v.triangleCount++;
  79289. }
  79290. }
  79291. var tStart = 0;
  79292. for (i = 0; i < this.vertices.length; ++i) {
  79293. this.vertices[i].triangleStart = tStart;
  79294. tStart += this.vertices[i].triangleCount;
  79295. this.vertices[i].triangleCount = 0;
  79296. }
  79297. var newReferences = new Array(this.triangles.length * 3);
  79298. for (i = 0; i < this.triangles.length; ++i) {
  79299. t = this.triangles[i];
  79300. for (j = 0; j < 3; ++j) {
  79301. v = t.vertices[j];
  79302. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  79303. v.triangleCount++;
  79304. }
  79305. }
  79306. this.references = newReferences;
  79307. if (identifyBorders) {
  79308. this.identifyBorder();
  79309. }
  79310. };
  79311. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  79312. var x = point.x;
  79313. var y = point.y;
  79314. var z = point.z;
  79315. 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
  79316. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  79317. };
  79318. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  79319. var q = vertex1.q.add(vertex2.q);
  79320. var border = vertex1.isBorder && vertex2.isBorder;
  79321. var error = 0;
  79322. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  79323. if (qDet !== 0 && !border) {
  79324. if (!pointResult) {
  79325. pointResult = BABYLON.Vector3.Zero();
  79326. }
  79327. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  79328. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  79329. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  79330. error = this.vertexError(q, pointResult);
  79331. }
  79332. else {
  79333. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  79334. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  79335. var error1 = this.vertexError(q, vertex1.position);
  79336. var error2 = this.vertexError(q, vertex2.position);
  79337. var error3 = this.vertexError(q, p3);
  79338. error = Math.min(error1, error2, error3);
  79339. if (error === error1) {
  79340. if (pointResult) {
  79341. pointResult.copyFrom(vertex1.position);
  79342. }
  79343. }
  79344. else if (error === error2) {
  79345. if (pointResult) {
  79346. pointResult.copyFrom(vertex2.position);
  79347. }
  79348. }
  79349. else {
  79350. if (pointResult) {
  79351. pointResult.copyFrom(p3);
  79352. }
  79353. }
  79354. }
  79355. return error;
  79356. };
  79357. return QuadraticErrorSimplification;
  79358. }());
  79359. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  79360. })(BABYLON || (BABYLON = {}));
  79361. //# sourceMappingURL=babylon.meshSimplification.js.map
  79362. var BABYLON;
  79363. (function (BABYLON) {
  79364. var MeshLODLevel = /** @class */ (function () {
  79365. function MeshLODLevel(distance, mesh) {
  79366. this.distance = distance;
  79367. this.mesh = mesh;
  79368. }
  79369. return MeshLODLevel;
  79370. }());
  79371. BABYLON.MeshLODLevel = MeshLODLevel;
  79372. })(BABYLON || (BABYLON = {}));
  79373. //# sourceMappingURL=babylon.meshLODLevel.js.map
  79374. var BABYLON;
  79375. (function (BABYLON) {
  79376. /**
  79377. * Defines the root class used to create scene optimization to use with SceneOptimizer
  79378. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79379. */
  79380. var SceneOptimization = /** @class */ (function () {
  79381. /**
  79382. * Creates the SceneOptimization object
  79383. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79384. * @param desc defines the description associated with the optimization
  79385. */
  79386. function SceneOptimization(
  79387. /**
  79388. * Defines the priority of this optimization (0 by default which means first in the list)
  79389. */
  79390. priority) {
  79391. if (priority === void 0) { priority = 0; }
  79392. this.priority = priority;
  79393. }
  79394. /**
  79395. * Gets a string describing the action executed by the current optimization
  79396. * @returns description string
  79397. */
  79398. SceneOptimization.prototype.getDescription = function () {
  79399. return "";
  79400. };
  79401. /**
  79402. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79403. * @param scene defines the current scene where to apply this optimization
  79404. * @param optimizer defines the current optimizer
  79405. * @returns true if everything that can be done was applied
  79406. */
  79407. SceneOptimization.prototype.apply = function (scene, optimizer) {
  79408. return true;
  79409. };
  79410. ;
  79411. return SceneOptimization;
  79412. }());
  79413. BABYLON.SceneOptimization = SceneOptimization;
  79414. /**
  79415. * Defines an optimization used to reduce the size of render target textures
  79416. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79417. */
  79418. var TextureOptimization = /** @class */ (function (_super) {
  79419. __extends(TextureOptimization, _super);
  79420. /**
  79421. * Creates the TextureOptimization object
  79422. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79423. * @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
  79424. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  79425. */
  79426. function TextureOptimization(
  79427. /**
  79428. * Defines the priority of this optimization (0 by default which means first in the list)
  79429. */
  79430. priority,
  79431. /**
  79432. * 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
  79433. */
  79434. maximumSize,
  79435. /**
  79436. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  79437. */
  79438. step) {
  79439. if (priority === void 0) { priority = 0; }
  79440. if (maximumSize === void 0) { maximumSize = 1024; }
  79441. if (step === void 0) { step = 0.5; }
  79442. var _this = _super.call(this, priority) || this;
  79443. _this.priority = priority;
  79444. _this.maximumSize = maximumSize;
  79445. _this.step = step;
  79446. return _this;
  79447. }
  79448. /**
  79449. * Gets a string describing the action executed by the current optimization
  79450. * @returns description string
  79451. */
  79452. TextureOptimization.prototype.getDescription = function () {
  79453. return "Reducing render target texture size to " + this.maximumSize;
  79454. };
  79455. /**
  79456. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79457. * @param scene defines the current scene where to apply this optimization
  79458. * @param optimizer defines the current optimizer
  79459. * @returns true if everything that can be done was applied
  79460. */
  79461. TextureOptimization.prototype.apply = function (scene, optimizer) {
  79462. var allDone = true;
  79463. for (var index = 0; index < scene.textures.length; index++) {
  79464. var texture = scene.textures[index];
  79465. if (!texture.canRescale || texture.getContext) {
  79466. continue;
  79467. }
  79468. var currentSize = texture.getSize();
  79469. var maxDimension = Math.max(currentSize.width, currentSize.height);
  79470. if (maxDimension > this.maximumSize) {
  79471. texture.scale(this.step);
  79472. allDone = false;
  79473. }
  79474. }
  79475. return allDone;
  79476. };
  79477. return TextureOptimization;
  79478. }(SceneOptimization));
  79479. BABYLON.TextureOptimization = TextureOptimization;
  79480. /**
  79481. * Defines an optimization used to increase or decrease the rendering resolution
  79482. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79483. */
  79484. var HardwareScalingOptimization = /** @class */ (function (_super) {
  79485. __extends(HardwareScalingOptimization, _super);
  79486. /**
  79487. * Creates the HardwareScalingOptimization object
  79488. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79489. * @param maximumScale defines the maximum scale to use (2 by default)
  79490. * @param step defines the step to use between two passes (0.5 by default)
  79491. */
  79492. function HardwareScalingOptimization(
  79493. /**
  79494. * Defines the priority of this optimization (0 by default which means first in the list)
  79495. */
  79496. priority,
  79497. /**
  79498. * Defines the maximum scale to use (2 by default)
  79499. */
  79500. maximumScale,
  79501. /**
  79502. * Defines the step to use between two passes (0.5 by default)
  79503. */
  79504. step) {
  79505. if (priority === void 0) { priority = 0; }
  79506. if (maximumScale === void 0) { maximumScale = 2; }
  79507. if (step === void 0) { step = 0.25; }
  79508. var _this = _super.call(this, priority) || this;
  79509. _this.priority = priority;
  79510. _this.maximumScale = maximumScale;
  79511. _this.step = step;
  79512. _this._currentScale = -1;
  79513. _this._directionOffset = 1;
  79514. return _this;
  79515. }
  79516. /**
  79517. * Gets a string describing the action executed by the current optimization
  79518. * @return description string
  79519. */
  79520. HardwareScalingOptimization.prototype.getDescription = function () {
  79521. return "Setting hardware scaling level to " + this._currentScale;
  79522. };
  79523. /**
  79524. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79525. * @param scene defines the current scene where to apply this optimization
  79526. * @param optimizer defines the current optimizer
  79527. * @returns true if everything that can be done was applied
  79528. */
  79529. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  79530. if (this._currentScale === -1) {
  79531. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  79532. if (this._currentScale > this.maximumScale) {
  79533. this._directionOffset = -1;
  79534. }
  79535. }
  79536. this._currentScale += this._directionOffset * this.step;
  79537. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  79538. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  79539. };
  79540. ;
  79541. return HardwareScalingOptimization;
  79542. }(SceneOptimization));
  79543. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  79544. /**
  79545. * Defines an optimization used to remove shadows
  79546. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79547. */
  79548. var ShadowsOptimization = /** @class */ (function (_super) {
  79549. __extends(ShadowsOptimization, _super);
  79550. function ShadowsOptimization() {
  79551. return _super !== null && _super.apply(this, arguments) || this;
  79552. }
  79553. /**
  79554. * Gets a string describing the action executed by the current optimization
  79555. * @return description string
  79556. */
  79557. ShadowsOptimization.prototype.getDescription = function () {
  79558. return "Turning shadows on/off";
  79559. };
  79560. /**
  79561. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79562. * @param scene defines the current scene where to apply this optimization
  79563. * @param optimizer defines the current optimizer
  79564. * @returns true if everything that can be done was applied
  79565. */
  79566. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  79567. scene.shadowsEnabled = optimizer.isInImprovementMode;
  79568. return true;
  79569. };
  79570. ;
  79571. return ShadowsOptimization;
  79572. }(SceneOptimization));
  79573. BABYLON.ShadowsOptimization = ShadowsOptimization;
  79574. /**
  79575. * Defines an optimization used to turn post-processes off
  79576. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79577. */
  79578. var PostProcessesOptimization = /** @class */ (function (_super) {
  79579. __extends(PostProcessesOptimization, _super);
  79580. function PostProcessesOptimization() {
  79581. return _super !== null && _super.apply(this, arguments) || this;
  79582. }
  79583. /**
  79584. * Gets a string describing the action executed by the current optimization
  79585. * @return description string
  79586. */
  79587. PostProcessesOptimization.prototype.getDescription = function () {
  79588. return "Turning post-processes on/off";
  79589. };
  79590. /**
  79591. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79592. * @param scene defines the current scene where to apply this optimization
  79593. * @param optimizer defines the current optimizer
  79594. * @returns true if everything that can be done was applied
  79595. */
  79596. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  79597. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  79598. return true;
  79599. };
  79600. ;
  79601. return PostProcessesOptimization;
  79602. }(SceneOptimization));
  79603. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  79604. /**
  79605. * Defines an optimization used to turn lens flares off
  79606. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79607. */
  79608. var LensFlaresOptimization = /** @class */ (function (_super) {
  79609. __extends(LensFlaresOptimization, _super);
  79610. function LensFlaresOptimization() {
  79611. return _super !== null && _super.apply(this, arguments) || this;
  79612. }
  79613. /**
  79614. * Gets a string describing the action executed by the current optimization
  79615. * @return description string
  79616. */
  79617. LensFlaresOptimization.prototype.getDescription = function () {
  79618. return "Turning lens flares on/off";
  79619. };
  79620. /**
  79621. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79622. * @param scene defines the current scene where to apply this optimization
  79623. * @param optimizer defines the current optimizer
  79624. * @returns true if everything that can be done was applied
  79625. */
  79626. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  79627. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  79628. return true;
  79629. };
  79630. ;
  79631. return LensFlaresOptimization;
  79632. }(SceneOptimization));
  79633. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  79634. /**
  79635. * Defines an optimization based on user defined callback.
  79636. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79637. */
  79638. var CustomOptimization = /** @class */ (function (_super) {
  79639. __extends(CustomOptimization, _super);
  79640. function CustomOptimization() {
  79641. return _super !== null && _super.apply(this, arguments) || this;
  79642. }
  79643. /**
  79644. * Gets a string describing the action executed by the current optimization
  79645. * @returns description string
  79646. */
  79647. CustomOptimization.prototype.getDescription = function () {
  79648. if (this.onGetDescription) {
  79649. return this.onGetDescription();
  79650. }
  79651. return "Running user defined callback";
  79652. };
  79653. /**
  79654. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79655. * @param scene defines the current scene where to apply this optimization
  79656. * @param optimizer defines the current optimizer
  79657. * @returns true if everything that can be done was applied
  79658. */
  79659. CustomOptimization.prototype.apply = function (scene, optimizer) {
  79660. if (this.onApply) {
  79661. return this.onApply(scene, optimizer);
  79662. }
  79663. return true;
  79664. };
  79665. ;
  79666. return CustomOptimization;
  79667. }(SceneOptimization));
  79668. BABYLON.CustomOptimization = CustomOptimization;
  79669. /**
  79670. * Defines an optimization used to turn particles off
  79671. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79672. */
  79673. var ParticlesOptimization = /** @class */ (function (_super) {
  79674. __extends(ParticlesOptimization, _super);
  79675. function ParticlesOptimization() {
  79676. return _super !== null && _super.apply(this, arguments) || this;
  79677. }
  79678. /**
  79679. * Gets a string describing the action executed by the current optimization
  79680. * @return description string
  79681. */
  79682. ParticlesOptimization.prototype.getDescription = function () {
  79683. return "Turning particles on/off";
  79684. };
  79685. /**
  79686. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79687. * @param scene defines the current scene where to apply this optimization
  79688. * @param optimizer defines the current optimizer
  79689. * @returns true if everything that can be done was applied
  79690. */
  79691. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  79692. scene.particlesEnabled = optimizer.isInImprovementMode;
  79693. return true;
  79694. };
  79695. ;
  79696. return ParticlesOptimization;
  79697. }(SceneOptimization));
  79698. BABYLON.ParticlesOptimization = ParticlesOptimization;
  79699. /**
  79700. * Defines an optimization used to turn render targets off
  79701. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79702. */
  79703. var RenderTargetsOptimization = /** @class */ (function (_super) {
  79704. __extends(RenderTargetsOptimization, _super);
  79705. function RenderTargetsOptimization() {
  79706. return _super !== null && _super.apply(this, arguments) || this;
  79707. }
  79708. /**
  79709. * Gets a string describing the action executed by the current optimization
  79710. * @return description string
  79711. */
  79712. RenderTargetsOptimization.prototype.getDescription = function () {
  79713. return "Turning render targets off";
  79714. };
  79715. /**
  79716. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79717. * @param scene defines the current scene where to apply this optimization
  79718. * @param optimizer defines the current optimizer
  79719. * @returns true if everything that can be done was applied
  79720. */
  79721. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  79722. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  79723. return true;
  79724. };
  79725. ;
  79726. return RenderTargetsOptimization;
  79727. }(SceneOptimization));
  79728. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  79729. /**
  79730. * Defines an optimization used to merge meshes with compatible materials
  79731. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79732. */
  79733. var MergeMeshesOptimization = /** @class */ (function (_super) {
  79734. __extends(MergeMeshesOptimization, _super);
  79735. function MergeMeshesOptimization() {
  79736. var _this = _super !== null && _super.apply(this, arguments) || this;
  79737. _this._canBeMerged = function (abstractMesh) {
  79738. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  79739. return false;
  79740. }
  79741. var mesh = abstractMesh;
  79742. if (!mesh.isVisible || !mesh.isEnabled()) {
  79743. return false;
  79744. }
  79745. if (mesh.instances.length > 0) {
  79746. return false;
  79747. }
  79748. if (mesh.skeleton || mesh.hasLODLevels) {
  79749. return false;
  79750. }
  79751. if (mesh.parent) {
  79752. return false;
  79753. }
  79754. return true;
  79755. };
  79756. return _this;
  79757. }
  79758. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  79759. /**
  79760. * Gets or sets a boolean which defines if optimization octree has to be updated
  79761. */
  79762. get: function () {
  79763. return MergeMeshesOptimization._UpdateSelectionTree;
  79764. },
  79765. /**
  79766. * Gets or sets a boolean which defines if optimization octree has to be updated
  79767. */
  79768. set: function (value) {
  79769. MergeMeshesOptimization._UpdateSelectionTree = value;
  79770. },
  79771. enumerable: true,
  79772. configurable: true
  79773. });
  79774. /**
  79775. * Gets a string describing the action executed by the current optimization
  79776. * @return description string
  79777. */
  79778. MergeMeshesOptimization.prototype.getDescription = function () {
  79779. return "Merging similar meshes together";
  79780. };
  79781. /**
  79782. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79783. * @param scene defines the current scene where to apply this optimization
  79784. * @param optimizer defines the current optimizer
  79785. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  79786. * @returns true if everything that can be done was applied
  79787. */
  79788. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  79789. var globalPool = scene.meshes.slice(0);
  79790. var globalLength = globalPool.length;
  79791. for (var index = 0; index < globalLength; index++) {
  79792. var currentPool = new Array();
  79793. var current = globalPool[index];
  79794. // Checks
  79795. if (!this._canBeMerged(current)) {
  79796. continue;
  79797. }
  79798. currentPool.push(current);
  79799. // Find compatible meshes
  79800. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  79801. var otherMesh = globalPool[subIndex];
  79802. if (!this._canBeMerged(otherMesh)) {
  79803. continue;
  79804. }
  79805. if (otherMesh.material !== current.material) {
  79806. continue;
  79807. }
  79808. if (otherMesh.checkCollisions !== current.checkCollisions) {
  79809. continue;
  79810. }
  79811. currentPool.push(otherMesh);
  79812. globalLength--;
  79813. globalPool.splice(subIndex, 1);
  79814. subIndex--;
  79815. }
  79816. if (currentPool.length < 2) {
  79817. continue;
  79818. }
  79819. // Merge meshes
  79820. BABYLON.Mesh.MergeMeshes(currentPool);
  79821. }
  79822. if (updateSelectionTree != undefined) {
  79823. if (updateSelectionTree) {
  79824. scene.createOrUpdateSelectionOctree();
  79825. }
  79826. }
  79827. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  79828. scene.createOrUpdateSelectionOctree();
  79829. }
  79830. return true;
  79831. };
  79832. ;
  79833. MergeMeshesOptimization._UpdateSelectionTree = false;
  79834. return MergeMeshesOptimization;
  79835. }(SceneOptimization));
  79836. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  79837. /**
  79838. * Defines a list of options used by SceneOptimizer
  79839. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79840. */
  79841. var SceneOptimizerOptions = /** @class */ (function () {
  79842. /**
  79843. * Creates a new list of options used by SceneOptimizer
  79844. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  79845. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  79846. */
  79847. function SceneOptimizerOptions(
  79848. /**
  79849. * Defines the target frame rate to reach (60 by default)
  79850. */
  79851. targetFrameRate,
  79852. /**
  79853. * Defines the interval between two checkes (2000ms by default)
  79854. */
  79855. trackerDuration) {
  79856. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  79857. if (trackerDuration === void 0) { trackerDuration = 2000; }
  79858. this.targetFrameRate = targetFrameRate;
  79859. this.trackerDuration = trackerDuration;
  79860. /**
  79861. * Gets the list of optimizations to apply
  79862. */
  79863. this.optimizations = new Array();
  79864. }
  79865. /**
  79866. * Add a new optimization
  79867. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  79868. * @returns the current SceneOptimizerOptions
  79869. */
  79870. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  79871. this.optimizations.push(optimization);
  79872. return this;
  79873. };
  79874. /**
  79875. * Add a new custom optimization
  79876. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  79877. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  79878. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79879. * @returns the current SceneOptimizerOptions
  79880. */
  79881. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  79882. if (priority === void 0) { priority = 0; }
  79883. var optimization = new CustomOptimization(priority);
  79884. optimization.onApply = onApply;
  79885. optimization.onGetDescription = onGetDescription;
  79886. this.optimizations.push(optimization);
  79887. return this;
  79888. };
  79889. /**
  79890. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  79891. * @param targetFrameRate defines the target frame rate (60 by default)
  79892. * @returns a SceneOptimizerOptions object
  79893. */
  79894. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  79895. var result = new SceneOptimizerOptions(targetFrameRate);
  79896. var priority = 0;
  79897. result.addOptimization(new MergeMeshesOptimization(priority));
  79898. result.addOptimization(new ShadowsOptimization(priority));
  79899. result.addOptimization(new LensFlaresOptimization(priority));
  79900. // Next priority
  79901. priority++;
  79902. result.addOptimization(new PostProcessesOptimization(priority));
  79903. result.addOptimization(new ParticlesOptimization(priority));
  79904. // Next priority
  79905. priority++;
  79906. result.addOptimization(new TextureOptimization(priority, 1024));
  79907. return result;
  79908. };
  79909. /**
  79910. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  79911. * @param targetFrameRate defines the target frame rate (60 by default)
  79912. * @returns a SceneOptimizerOptions object
  79913. */
  79914. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  79915. var result = new SceneOptimizerOptions(targetFrameRate);
  79916. var priority = 0;
  79917. result.addOptimization(new MergeMeshesOptimization(priority));
  79918. result.addOptimization(new ShadowsOptimization(priority));
  79919. result.addOptimization(new LensFlaresOptimization(priority));
  79920. // Next priority
  79921. priority++;
  79922. result.addOptimization(new PostProcessesOptimization(priority));
  79923. result.addOptimization(new ParticlesOptimization(priority));
  79924. // Next priority
  79925. priority++;
  79926. result.addOptimization(new TextureOptimization(priority, 512));
  79927. // Next priority
  79928. priority++;
  79929. result.addOptimization(new RenderTargetsOptimization(priority));
  79930. // Next priority
  79931. priority++;
  79932. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  79933. return result;
  79934. };
  79935. /**
  79936. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  79937. * @param targetFrameRate defines the target frame rate (60 by default)
  79938. * @returns a SceneOptimizerOptions object
  79939. */
  79940. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  79941. var result = new SceneOptimizerOptions(targetFrameRate);
  79942. var priority = 0;
  79943. result.addOptimization(new MergeMeshesOptimization(priority));
  79944. result.addOptimization(new ShadowsOptimization(priority));
  79945. result.addOptimization(new LensFlaresOptimization(priority));
  79946. // Next priority
  79947. priority++;
  79948. result.addOptimization(new PostProcessesOptimization(priority));
  79949. result.addOptimization(new ParticlesOptimization(priority));
  79950. // Next priority
  79951. priority++;
  79952. result.addOptimization(new TextureOptimization(priority, 256));
  79953. // Next priority
  79954. priority++;
  79955. result.addOptimization(new RenderTargetsOptimization(priority));
  79956. // Next priority
  79957. priority++;
  79958. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  79959. return result;
  79960. };
  79961. return SceneOptimizerOptions;
  79962. }());
  79963. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  79964. /**
  79965. * Class used to run optimizations in order to reach a target frame rate
  79966. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79967. */
  79968. var SceneOptimizer = /** @class */ (function () {
  79969. /**
  79970. * Creates a new SceneOptimizer
  79971. * @param scene defines the scene to work on
  79972. * @param options defines the options to use with the SceneOptimizer
  79973. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  79974. * @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)
  79975. */
  79976. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  79977. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  79978. if (improvementMode === void 0) { improvementMode = false; }
  79979. var _this = this;
  79980. this._isRunning = false;
  79981. this._currentPriorityLevel = 0;
  79982. this._targetFrameRate = 60;
  79983. this._trackerDuration = 2000;
  79984. this._currentFrameRate = 0;
  79985. this._improvementMode = false;
  79986. /**
  79987. * Defines an observable called when the optimizer reaches the target frame rate
  79988. */
  79989. this.onSuccessObservable = new BABYLON.Observable();
  79990. /**
  79991. * Defines an observable called when the optimizer enables an optimization
  79992. */
  79993. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  79994. /**
  79995. * Defines an observable called when the optimizer is not able to reach the target frame rate
  79996. */
  79997. this.onFailureObservable = new BABYLON.Observable();
  79998. if (!options) {
  79999. this._options = new SceneOptimizerOptions();
  80000. }
  80001. else {
  80002. this._options = options;
  80003. }
  80004. if (this._options.targetFrameRate) {
  80005. this._targetFrameRate = this._options.targetFrameRate;
  80006. }
  80007. if (this._options.trackerDuration) {
  80008. this._trackerDuration = this._options.trackerDuration;
  80009. }
  80010. if (autoGeneratePriorities) {
  80011. var priority = 0;
  80012. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  80013. var optim = _a[_i];
  80014. optim.priority = priority++;
  80015. }
  80016. }
  80017. this._improvementMode = improvementMode;
  80018. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80019. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  80020. _this._sceneDisposeObserver = null;
  80021. _this.dispose();
  80022. });
  80023. }
  80024. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  80025. /**
  80026. * Gets a boolean indicating if the optimizer is in improvement mode
  80027. */
  80028. get: function () {
  80029. return this._improvementMode;
  80030. },
  80031. enumerable: true,
  80032. configurable: true
  80033. });
  80034. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  80035. /**
  80036. * Gets the current priority level (0 at start)
  80037. */
  80038. get: function () {
  80039. return this._currentPriorityLevel;
  80040. },
  80041. enumerable: true,
  80042. configurable: true
  80043. });
  80044. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  80045. /**
  80046. * Gets the current frame rate checked by the SceneOptimizer
  80047. */
  80048. get: function () {
  80049. return this._currentFrameRate;
  80050. },
  80051. enumerable: true,
  80052. configurable: true
  80053. });
  80054. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  80055. /**
  80056. * Gets or sets the current target frame rate (60 by default)
  80057. */
  80058. get: function () {
  80059. return this._targetFrameRate;
  80060. },
  80061. /**
  80062. * Gets or sets the current target frame rate (60 by default)
  80063. */
  80064. set: function (value) {
  80065. this._targetFrameRate = value;
  80066. },
  80067. enumerable: true,
  80068. configurable: true
  80069. });
  80070. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  80071. /**
  80072. * Gets or sets the current interval between two checks (every 2000ms by default)
  80073. */
  80074. get: function () {
  80075. return this._trackerDuration;
  80076. },
  80077. /**
  80078. * Gets or sets the current interval between two checks (every 2000ms by default)
  80079. */
  80080. set: function (value) {
  80081. this._trackerDuration = value;
  80082. },
  80083. enumerable: true,
  80084. configurable: true
  80085. });
  80086. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  80087. /**
  80088. * Gets the list of active optimizations
  80089. */
  80090. get: function () {
  80091. return this._options.optimizations;
  80092. },
  80093. enumerable: true,
  80094. configurable: true
  80095. });
  80096. /**
  80097. * Stops the current optimizer
  80098. */
  80099. SceneOptimizer.prototype.stop = function () {
  80100. this._isRunning = false;
  80101. };
  80102. /**
  80103. * Reset the optimizer to initial step (current priority level = 0)
  80104. */
  80105. SceneOptimizer.prototype.reset = function () {
  80106. this._currentPriorityLevel = 0;
  80107. };
  80108. /**
  80109. * Start the optimizer. By default it will try to reach a specific framerate
  80110. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  80111. */
  80112. SceneOptimizer.prototype.start = function () {
  80113. var _this = this;
  80114. if (this._isRunning) {
  80115. return;
  80116. }
  80117. this._isRunning = true;
  80118. // Let's wait for the scene to be ready before running our check
  80119. this._scene.executeWhenReady(function () {
  80120. setTimeout(function () {
  80121. _this._checkCurrentState();
  80122. }, _this._trackerDuration);
  80123. });
  80124. };
  80125. SceneOptimizer.prototype._checkCurrentState = function () {
  80126. var _this = this;
  80127. if (!this._isRunning) {
  80128. return;
  80129. }
  80130. var scene = this._scene;
  80131. var options = this._options;
  80132. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  80133. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  80134. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  80135. this._isRunning = false;
  80136. this.onSuccessObservable.notifyObservers(this);
  80137. return;
  80138. }
  80139. // Apply current level of optimizations
  80140. var allDone = true;
  80141. var noOptimizationApplied = true;
  80142. for (var index = 0; index < options.optimizations.length; index++) {
  80143. var optimization = options.optimizations[index];
  80144. if (optimization.priority === this._currentPriorityLevel) {
  80145. noOptimizationApplied = false;
  80146. allDone = allDone && optimization.apply(scene, this);
  80147. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  80148. }
  80149. }
  80150. // If no optimization was applied, this is a failure :(
  80151. if (noOptimizationApplied) {
  80152. this._isRunning = false;
  80153. this.onFailureObservable.notifyObservers(this);
  80154. return;
  80155. }
  80156. // If all optimizations were done, move to next level
  80157. if (allDone) {
  80158. this._currentPriorityLevel++;
  80159. }
  80160. // Let's the system running for a specific amount of time before checking FPS
  80161. scene.executeWhenReady(function () {
  80162. setTimeout(function () {
  80163. _this._checkCurrentState();
  80164. }, _this._trackerDuration);
  80165. });
  80166. };
  80167. /**
  80168. * Release all resources
  80169. */
  80170. SceneOptimizer.prototype.dispose = function () {
  80171. this.stop();
  80172. this.onSuccessObservable.clear();
  80173. this.onFailureObservable.clear();
  80174. this.onNewOptimizationAppliedObservable.clear();
  80175. if (this._sceneDisposeObserver) {
  80176. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  80177. }
  80178. };
  80179. /**
  80180. * Helper function to create a SceneOptimizer with one single line of code
  80181. * @param scene defines the scene to work on
  80182. * @param options defines the options to use with the SceneOptimizer
  80183. * @param onSuccess defines a callback to call on success
  80184. * @param onFailure defines a callback to call on failure
  80185. * @returns the new SceneOptimizer object
  80186. */
  80187. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  80188. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  80189. if (onSuccess) {
  80190. optimizer.onSuccessObservable.add(function () {
  80191. onSuccess();
  80192. });
  80193. }
  80194. if (onFailure) {
  80195. optimizer.onFailureObservable.add(function () {
  80196. onFailure();
  80197. });
  80198. }
  80199. optimizer.start();
  80200. return optimizer;
  80201. };
  80202. return SceneOptimizer;
  80203. }());
  80204. BABYLON.SceneOptimizer = SceneOptimizer;
  80205. })(BABYLON || (BABYLON = {}));
  80206. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  80207. var BABYLON;
  80208. (function (BABYLON) {
  80209. var OutlineRenderer = /** @class */ (function () {
  80210. function OutlineRenderer(scene) {
  80211. this.zOffset = 1;
  80212. this._scene = scene;
  80213. }
  80214. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  80215. var _this = this;
  80216. if (useOverlay === void 0) { useOverlay = false; }
  80217. var scene = this._scene;
  80218. var engine = this._scene.getEngine();
  80219. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  80220. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  80221. return;
  80222. }
  80223. var mesh = subMesh.getRenderingMesh();
  80224. var material = subMesh.getMaterial();
  80225. if (!material || !scene.activeCamera) {
  80226. return;
  80227. }
  80228. engine.enableEffect(this._effect);
  80229. // Logarithmic depth
  80230. if (material.useLogarithmicDepth) {
  80231. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  80232. }
  80233. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  80234. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  80235. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  80236. // Bones
  80237. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80238. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80239. }
  80240. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  80241. // Alpha test
  80242. if (material && material.needAlphaTesting()) {
  80243. var alphaTexture = material.getAlphaTestTexture();
  80244. if (alphaTexture) {
  80245. this._effect.setTexture("diffuseSampler", alphaTexture);
  80246. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80247. }
  80248. }
  80249. engine.setZOffset(-this.zOffset);
  80250. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  80251. engine.setZOffset(0);
  80252. };
  80253. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  80254. var defines = [];
  80255. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  80256. var mesh = subMesh.getMesh();
  80257. var material = subMesh.getMaterial();
  80258. if (material) {
  80259. // Alpha test
  80260. if (material.needAlphaTesting()) {
  80261. defines.push("#define ALPHATEST");
  80262. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80263. attribs.push(BABYLON.VertexBuffer.UVKind);
  80264. defines.push("#define UV1");
  80265. }
  80266. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80267. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80268. defines.push("#define UV2");
  80269. }
  80270. }
  80271. //Logarithmic depth
  80272. if (material.useLogarithmicDepth) {
  80273. defines.push("#define LOGARITHMICDEPTH");
  80274. }
  80275. }
  80276. // Bones
  80277. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80278. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80279. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80280. if (mesh.numBoneInfluencers > 4) {
  80281. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80282. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80283. }
  80284. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80285. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80286. }
  80287. else {
  80288. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80289. }
  80290. // Instances
  80291. if (useInstances) {
  80292. defines.push("#define INSTANCES");
  80293. attribs.push("world0");
  80294. attribs.push("world1");
  80295. attribs.push("world2");
  80296. attribs.push("world3");
  80297. }
  80298. // Get correct effect
  80299. var join = defines.join("\n");
  80300. if (this._cachedDefines !== join) {
  80301. this._cachedDefines = join;
  80302. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  80303. }
  80304. return this._effect.isReady();
  80305. };
  80306. return OutlineRenderer;
  80307. }());
  80308. BABYLON.OutlineRenderer = OutlineRenderer;
  80309. })(BABYLON || (BABYLON = {}));
  80310. //# sourceMappingURL=babylon.outlineRenderer.js.map
  80311. var BABYLON;
  80312. (function (BABYLON) {
  80313. var FaceAdjacencies = /** @class */ (function () {
  80314. function FaceAdjacencies() {
  80315. this.edges = new Array();
  80316. this.edgesConnectedCount = 0;
  80317. }
  80318. return FaceAdjacencies;
  80319. }());
  80320. var EdgesRenderer = /** @class */ (function () {
  80321. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  80322. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  80323. if (epsilon === void 0) { epsilon = 0.95; }
  80324. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  80325. this.edgesWidthScalerForOrthographic = 1000.0;
  80326. this.edgesWidthScalerForPerspective = 50.0;
  80327. this._linesPositions = new Array();
  80328. this._linesNormals = new Array();
  80329. this._linesIndices = new Array();
  80330. this._buffers = {};
  80331. this._checkVerticesInsteadOfIndices = false;
  80332. this._source = source;
  80333. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  80334. this._epsilon = epsilon;
  80335. this._prepareRessources();
  80336. this._generateEdgesLines();
  80337. }
  80338. EdgesRenderer.prototype._prepareRessources = function () {
  80339. if (this._lineShader) {
  80340. return;
  80341. }
  80342. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  80343. attributes: ["position", "normal"],
  80344. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  80345. });
  80346. this._lineShader.disableDepthWrite = true;
  80347. this._lineShader.backFaceCulling = false;
  80348. };
  80349. EdgesRenderer.prototype._rebuild = function () {
  80350. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  80351. if (buffer) {
  80352. buffer._rebuild();
  80353. }
  80354. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  80355. if (buffer) {
  80356. buffer._rebuild();
  80357. }
  80358. var scene = this._source.getScene();
  80359. var engine = scene.getEngine();
  80360. this._ib = engine.createIndexBuffer(this._linesIndices);
  80361. };
  80362. EdgesRenderer.prototype.dispose = function () {
  80363. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  80364. if (buffer) {
  80365. buffer.dispose();
  80366. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  80367. }
  80368. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  80369. if (buffer) {
  80370. buffer.dispose();
  80371. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  80372. }
  80373. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  80374. this._lineShader.dispose();
  80375. };
  80376. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  80377. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  80378. return 0;
  80379. }
  80380. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  80381. return 1;
  80382. }
  80383. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  80384. return 2;
  80385. }
  80386. return -1;
  80387. };
  80388. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  80389. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  80390. return 0;
  80391. }
  80392. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  80393. return 1;
  80394. }
  80395. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  80396. return 2;
  80397. }
  80398. return -1;
  80399. };
  80400. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  80401. var needToCreateLine;
  80402. if (edge === undefined) {
  80403. needToCreateLine = true;
  80404. }
  80405. else {
  80406. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  80407. needToCreateLine = dotProduct < this._epsilon;
  80408. }
  80409. if (needToCreateLine) {
  80410. var offset = this._linesPositions.length / 3;
  80411. var normal = p0.subtract(p1);
  80412. normal.normalize();
  80413. // Positions
  80414. this._linesPositions.push(p0.x);
  80415. this._linesPositions.push(p0.y);
  80416. this._linesPositions.push(p0.z);
  80417. this._linesPositions.push(p0.x);
  80418. this._linesPositions.push(p0.y);
  80419. this._linesPositions.push(p0.z);
  80420. this._linesPositions.push(p1.x);
  80421. this._linesPositions.push(p1.y);
  80422. this._linesPositions.push(p1.z);
  80423. this._linesPositions.push(p1.x);
  80424. this._linesPositions.push(p1.y);
  80425. this._linesPositions.push(p1.z);
  80426. // Normals
  80427. this._linesNormals.push(p1.x);
  80428. this._linesNormals.push(p1.y);
  80429. this._linesNormals.push(p1.z);
  80430. this._linesNormals.push(-1);
  80431. this._linesNormals.push(p1.x);
  80432. this._linesNormals.push(p1.y);
  80433. this._linesNormals.push(p1.z);
  80434. this._linesNormals.push(1);
  80435. this._linesNormals.push(p0.x);
  80436. this._linesNormals.push(p0.y);
  80437. this._linesNormals.push(p0.z);
  80438. this._linesNormals.push(-1);
  80439. this._linesNormals.push(p0.x);
  80440. this._linesNormals.push(p0.y);
  80441. this._linesNormals.push(p0.z);
  80442. this._linesNormals.push(1);
  80443. // Indices
  80444. this._linesIndices.push(offset);
  80445. this._linesIndices.push(offset + 1);
  80446. this._linesIndices.push(offset + 2);
  80447. this._linesIndices.push(offset);
  80448. this._linesIndices.push(offset + 2);
  80449. this._linesIndices.push(offset + 3);
  80450. }
  80451. };
  80452. EdgesRenderer.prototype._generateEdgesLines = function () {
  80453. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80454. var indices = this._source.getIndices();
  80455. if (!indices || !positions) {
  80456. return;
  80457. }
  80458. // First let's find adjacencies
  80459. var adjacencies = new Array();
  80460. var faceNormals = new Array();
  80461. var index;
  80462. var faceAdjacencies;
  80463. // Prepare faces
  80464. for (index = 0; index < indices.length; index += 3) {
  80465. faceAdjacencies = new FaceAdjacencies();
  80466. var p0Index = indices[index];
  80467. var p1Index = indices[index + 1];
  80468. var p2Index = indices[index + 2];
  80469. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  80470. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  80471. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  80472. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  80473. faceNormal.normalize();
  80474. faceNormals.push(faceNormal);
  80475. adjacencies.push(faceAdjacencies);
  80476. }
  80477. // Scan
  80478. for (index = 0; index < adjacencies.length; index++) {
  80479. faceAdjacencies = adjacencies[index];
  80480. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  80481. var otherFaceAdjacencies = adjacencies[otherIndex];
  80482. if (faceAdjacencies.edgesConnectedCount === 3) {
  80483. break;
  80484. }
  80485. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  80486. continue;
  80487. }
  80488. var otherP0 = indices[otherIndex * 3];
  80489. var otherP1 = indices[otherIndex * 3 + 1];
  80490. var otherP2 = indices[otherIndex * 3 + 2];
  80491. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  80492. var otherEdgeIndex = 0;
  80493. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  80494. continue;
  80495. }
  80496. switch (edgeIndex) {
  80497. case 0:
  80498. if (this._checkVerticesInsteadOfIndices) {
  80499. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  80500. }
  80501. else {
  80502. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  80503. }
  80504. break;
  80505. case 1:
  80506. if (this._checkVerticesInsteadOfIndices) {
  80507. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  80508. }
  80509. else {
  80510. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  80511. }
  80512. break;
  80513. case 2:
  80514. if (this._checkVerticesInsteadOfIndices) {
  80515. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  80516. }
  80517. else {
  80518. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  80519. }
  80520. break;
  80521. }
  80522. if (otherEdgeIndex === -1) {
  80523. continue;
  80524. }
  80525. faceAdjacencies.edges[edgeIndex] = otherIndex;
  80526. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  80527. faceAdjacencies.edgesConnectedCount++;
  80528. otherFaceAdjacencies.edgesConnectedCount++;
  80529. if (faceAdjacencies.edgesConnectedCount === 3) {
  80530. break;
  80531. }
  80532. }
  80533. }
  80534. }
  80535. // Create lines
  80536. for (index = 0; index < adjacencies.length; index++) {
  80537. // 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
  80538. var current = adjacencies[index];
  80539. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  80540. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  80541. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  80542. }
  80543. // Merge into a single mesh
  80544. var engine = this._source.getScene().getEngine();
  80545. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  80546. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  80547. this._ib = engine.createIndexBuffer(this._linesIndices);
  80548. this._indicesCount = this._linesIndices.length;
  80549. };
  80550. EdgesRenderer.prototype.render = function () {
  80551. var scene = this._source.getScene();
  80552. if (!this._lineShader.isReady() || !scene.activeCamera) {
  80553. return;
  80554. }
  80555. var engine = scene.getEngine();
  80556. this._lineShader._preBind();
  80557. // VBOs
  80558. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  80559. scene.resetCachedMaterial();
  80560. this._lineShader.setColor4("color", this._source.edgesColor);
  80561. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  80562. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  80563. }
  80564. else {
  80565. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  80566. }
  80567. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  80568. this._lineShader.bind(this._source.getWorldMatrix());
  80569. // Draw order
  80570. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  80571. this._lineShader.unbind();
  80572. engine.setDepthWrite(true);
  80573. };
  80574. return EdgesRenderer;
  80575. }());
  80576. BABYLON.EdgesRenderer = EdgesRenderer;
  80577. })(BABYLON || (BABYLON = {}));
  80578. //# sourceMappingURL=babylon.edgesRenderer.js.map
  80579. var BABYLON;
  80580. (function (BABYLON) {
  80581. /**
  80582. * Special Glow Blur post process only blurring the alpha channel
  80583. * It enforces keeping the most luminous color in the color channel.
  80584. */
  80585. var GlowBlurPostProcess = /** @class */ (function (_super) {
  80586. __extends(GlowBlurPostProcess, _super);
  80587. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  80588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80589. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  80590. _this.direction = direction;
  80591. _this.kernel = kernel;
  80592. _this.onApplyObservable.add(function (effect) {
  80593. effect.setFloat2("screenSize", _this.width, _this.height);
  80594. effect.setVector2("direction", _this.direction);
  80595. effect.setFloat("blurWidth", _this.kernel);
  80596. });
  80597. return _this;
  80598. }
  80599. return GlowBlurPostProcess;
  80600. }(BABYLON.PostProcess));
  80601. /**
  80602. * The highlight layer Helps adding a glow effect around a mesh.
  80603. *
  80604. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  80605. * glowy meshes to your scene.
  80606. *
  80607. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  80608. */
  80609. var HighlightLayer = /** @class */ (function () {
  80610. /**
  80611. * Instantiates a new highlight Layer and references it to the scene..
  80612. * @param name The name of the layer
  80613. * @param scene The scene to use the layer in
  80614. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  80615. */
  80616. function HighlightLayer(name, scene, options) {
  80617. this.name = name;
  80618. this._vertexBuffers = {};
  80619. this._mainTextureDesiredSize = { width: 0, height: 0 };
  80620. this._meshes = {};
  80621. this._maxSize = 0;
  80622. this._shouldRender = false;
  80623. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  80624. this._excludedMeshes = {};
  80625. /**
  80626. * Specifies whether or not the inner glow is ACTIVE in the layer.
  80627. */
  80628. this.innerGlow = true;
  80629. /**
  80630. * Specifies whether or not the outer glow is ACTIVE in the layer.
  80631. */
  80632. this.outerGlow = true;
  80633. /**
  80634. * Specifies wether the highlight layer is enabled or not.
  80635. */
  80636. this.isEnabled = true;
  80637. /**
  80638. * An event triggered when the highlight layer has been disposed.
  80639. * @type {BABYLON.Observable}
  80640. */
  80641. this.onDisposeObservable = new BABYLON.Observable();
  80642. /**
  80643. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  80644. * @type {BABYLON.Observable}
  80645. */
  80646. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  80647. /**
  80648. * An event triggered when the highlight layer is being blurred.
  80649. * @type {BABYLON.Observable}
  80650. */
  80651. this.onBeforeBlurObservable = new BABYLON.Observable();
  80652. /**
  80653. * An event triggered when the highlight layer has been blurred.
  80654. * @type {BABYLON.Observable}
  80655. */
  80656. this.onAfterBlurObservable = new BABYLON.Observable();
  80657. /**
  80658. * An event triggered when the glowing blurred texture is being merged in the scene.
  80659. * @type {BABYLON.Observable}
  80660. */
  80661. this.onBeforeComposeObservable = new BABYLON.Observable();
  80662. /**
  80663. * An event triggered when the glowing blurred texture has been merged in the scene.
  80664. * @type {BABYLON.Observable}
  80665. */
  80666. this.onAfterComposeObservable = new BABYLON.Observable();
  80667. /**
  80668. * An event triggered when the highlight layer changes its size.
  80669. * @type {BABYLON.Observable}
  80670. */
  80671. this.onSizeChangedObservable = new BABYLON.Observable();
  80672. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80673. var engine = scene.getEngine();
  80674. this._engine = engine;
  80675. this._maxSize = this._engine.getCaps().maxTextureSize;
  80676. this._scene.highlightLayers.push(this);
  80677. // Warn on stencil.
  80678. if (!this._engine.isStencilEnable) {
  80679. 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 }");
  80680. }
  80681. // Adapt options
  80682. this._options = options || {
  80683. mainTextureRatio: 0.5,
  80684. blurTextureSizeRatio: 0.5,
  80685. blurHorizontalSize: 1.0,
  80686. blurVerticalSize: 1.0,
  80687. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  80688. camera: null
  80689. };
  80690. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  80691. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  80692. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  80693. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  80694. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  80695. // VBO
  80696. var vertices = [];
  80697. vertices.push(1, 1);
  80698. vertices.push(-1, 1);
  80699. vertices.push(-1, -1);
  80700. vertices.push(1, -1);
  80701. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80702. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  80703. this._createIndexBuffer();
  80704. // Effect
  80705. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  80706. // Render target
  80707. this.setMainTextureSize();
  80708. // Create Textures and post processes
  80709. this.createTextureAndPostProcesses();
  80710. }
  80711. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  80712. /**
  80713. * Gets the horizontal size of the blur.
  80714. */
  80715. get: function () {
  80716. return this._horizontalBlurPostprocess.kernel;
  80717. },
  80718. /**
  80719. * Specifies the horizontal size of the blur.
  80720. */
  80721. set: function (value) {
  80722. this._horizontalBlurPostprocess.kernel = value;
  80723. },
  80724. enumerable: true,
  80725. configurable: true
  80726. });
  80727. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  80728. /**
  80729. * Gets the vertical size of the blur.
  80730. */
  80731. get: function () {
  80732. return this._verticalBlurPostprocess.kernel;
  80733. },
  80734. /**
  80735. * Specifies the vertical size of the blur.
  80736. */
  80737. set: function (value) {
  80738. this._verticalBlurPostprocess.kernel = value;
  80739. },
  80740. enumerable: true,
  80741. configurable: true
  80742. });
  80743. Object.defineProperty(HighlightLayer.prototype, "camera", {
  80744. /**
  80745. * Gets the camera attached to the layer.
  80746. */
  80747. get: function () {
  80748. return this._options.camera;
  80749. },
  80750. enumerable: true,
  80751. configurable: true
  80752. });
  80753. HighlightLayer.prototype._createIndexBuffer = function () {
  80754. var engine = this._scene.getEngine();
  80755. // Indices
  80756. var indices = [];
  80757. indices.push(0);
  80758. indices.push(1);
  80759. indices.push(2);
  80760. indices.push(0);
  80761. indices.push(2);
  80762. indices.push(3);
  80763. this._indexBuffer = engine.createIndexBuffer(indices);
  80764. };
  80765. HighlightLayer.prototype._rebuild = function () {
  80766. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80767. if (vb) {
  80768. vb._rebuild();
  80769. }
  80770. this._createIndexBuffer();
  80771. };
  80772. /**
  80773. * Creates the render target textures and post processes used in the highlight layer.
  80774. */
  80775. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  80776. var _this = this;
  80777. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  80778. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  80779. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  80780. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  80781. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  80782. width: this._mainTextureDesiredSize.width,
  80783. height: this._mainTextureDesiredSize.height
  80784. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80785. this._mainTexture.activeCamera = this._options.camera;
  80786. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80787. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80788. this._mainTexture.anisotropicFilteringLevel = 1;
  80789. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80790. this._mainTexture.renderParticles = false;
  80791. this._mainTexture.renderList = null;
  80792. this._mainTexture.ignoreCameraViewport = true;
  80793. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  80794. width: blurTextureWidth,
  80795. height: blurTextureHeight
  80796. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80797. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80798. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80799. this._blurTexture.anisotropicFilteringLevel = 16;
  80800. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80801. this._blurTexture.renderParticles = false;
  80802. this._blurTexture.ignoreCameraViewport = true;
  80803. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80804. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  80805. effect.setTexture("textureSampler", _this._mainTexture);
  80806. });
  80807. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  80808. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80809. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80810. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80811. });
  80812. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80813. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80814. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80815. });
  80816. }
  80817. else {
  80818. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80819. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80820. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80821. });
  80822. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80823. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80824. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80825. });
  80826. }
  80827. this._mainTexture.onAfterUnbindObservable.add(function () {
  80828. _this.onBeforeBlurObservable.notifyObservers(_this);
  80829. var internalTexture = _this._blurTexture.getInternalTexture();
  80830. if (internalTexture) {
  80831. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  80832. }
  80833. _this.onAfterBlurObservable.notifyObservers(_this);
  80834. });
  80835. // Custom render function
  80836. var renderSubMesh = function (subMesh) {
  80837. if (!_this._meshes) {
  80838. return;
  80839. }
  80840. var material = subMesh.getMaterial();
  80841. var mesh = subMesh.getRenderingMesh();
  80842. var scene = _this._scene;
  80843. var engine = scene.getEngine();
  80844. if (!material) {
  80845. return;
  80846. }
  80847. // Do not block in blend mode.
  80848. if (material.needAlphaBlendingForMesh(mesh)) {
  80849. return;
  80850. }
  80851. // Culling
  80852. engine.setState(material.backFaceCulling);
  80853. // Managing instances
  80854. var batch = mesh._getInstancesRenderList(subMesh._id);
  80855. if (batch.mustReturn) {
  80856. return;
  80857. }
  80858. // Excluded Mesh
  80859. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  80860. return;
  80861. }
  80862. ;
  80863. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  80864. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  80865. var emissiveTexture = null;
  80866. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80867. emissiveTexture = material.emissiveTexture;
  80868. }
  80869. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  80870. engine.enableEffect(_this._glowMapGenerationEffect);
  80871. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  80872. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  80873. if (highlightLayerMesh) {
  80874. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  80875. }
  80876. else {
  80877. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  80878. }
  80879. // Alpha test
  80880. if (material && material.needAlphaTesting()) {
  80881. var alphaTexture = material.getAlphaTestTexture();
  80882. if (alphaTexture) {
  80883. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  80884. var textureMatrix = alphaTexture.getTextureMatrix();
  80885. if (textureMatrix) {
  80886. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  80887. }
  80888. }
  80889. }
  80890. // Glow emissive only
  80891. if (emissiveTexture) {
  80892. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  80893. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  80894. }
  80895. // Bones
  80896. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80897. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80898. }
  80899. // Draw
  80900. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  80901. }
  80902. else {
  80903. // Need to reset refresh rate of the shadowMap
  80904. _this._mainTexture.resetRefreshCounter();
  80905. }
  80906. };
  80907. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80908. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  80909. var index;
  80910. var engine = _this._scene.getEngine();
  80911. if (depthOnlySubMeshes.length) {
  80912. engine.setColorWrite(false);
  80913. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80914. renderSubMesh(depthOnlySubMeshes.data[index]);
  80915. }
  80916. engine.setColorWrite(true);
  80917. }
  80918. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80919. renderSubMesh(opaqueSubMeshes.data[index]);
  80920. }
  80921. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80922. renderSubMesh(alphaTestSubMeshes.data[index]);
  80923. }
  80924. for (index = 0; index < transparentSubMeshes.length; index++) {
  80925. renderSubMesh(transparentSubMeshes.data[index]);
  80926. }
  80927. };
  80928. this._mainTexture.onClearObservable.add(function (engine) {
  80929. engine.clear(HighlightLayer.neutralColor, true, true, true);
  80930. });
  80931. };
  80932. /**
  80933. * Checks for the readiness of the element composing the layer.
  80934. * @param subMesh the mesh to check for
  80935. * @param useInstances specify wether or not to use instances to render the mesh
  80936. * @param emissiveTexture the associated emissive texture used to generate the glow
  80937. * @return true if ready otherwise, false
  80938. */
  80939. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  80940. var material = subMesh.getMaterial();
  80941. var mesh = subMesh.getRenderingMesh();
  80942. if (!material || !mesh || !this._meshes) {
  80943. return false;
  80944. }
  80945. var emissiveTexture = null;
  80946. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  80947. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80948. emissiveTexture = material.emissiveTexture;
  80949. }
  80950. return this._isReady(subMesh, useInstances, emissiveTexture);
  80951. };
  80952. /**
  80953. * Checks for the readiness of the element composing the layer.
  80954. * @param subMesh the mesh to check for
  80955. * @param useInstances specify wether or not to use instances to render the mesh
  80956. * @param emissiveTexture the associated emissive texture used to generate the glow
  80957. * @return true if ready otherwise, false
  80958. */
  80959. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  80960. var material = subMesh.getMaterial();
  80961. if (!material) {
  80962. return false;
  80963. }
  80964. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  80965. return false;
  80966. }
  80967. var defines = [];
  80968. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80969. var mesh = subMesh.getMesh();
  80970. var uv1 = false;
  80971. var uv2 = false;
  80972. // Alpha test
  80973. if (material && material.needAlphaTesting()) {
  80974. var alphaTexture = material.getAlphaTestTexture();
  80975. if (alphaTexture) {
  80976. defines.push("#define ALPHATEST");
  80977. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80978. alphaTexture.coordinatesIndex === 1) {
  80979. defines.push("#define DIFFUSEUV2");
  80980. uv2 = true;
  80981. }
  80982. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80983. defines.push("#define DIFFUSEUV1");
  80984. uv1 = true;
  80985. }
  80986. }
  80987. }
  80988. // Emissive
  80989. if (emissiveTexture) {
  80990. defines.push("#define EMISSIVE");
  80991. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80992. emissiveTexture.coordinatesIndex === 1) {
  80993. defines.push("#define EMISSIVEUV2");
  80994. uv2 = true;
  80995. }
  80996. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80997. defines.push("#define EMISSIVEUV1");
  80998. uv1 = true;
  80999. }
  81000. }
  81001. if (uv1) {
  81002. attribs.push(BABYLON.VertexBuffer.UVKind);
  81003. defines.push("#define UV1");
  81004. }
  81005. if (uv2) {
  81006. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81007. defines.push("#define UV2");
  81008. }
  81009. // Bones
  81010. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81011. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81012. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81013. if (mesh.numBoneInfluencers > 4) {
  81014. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81015. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81016. }
  81017. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81018. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  81019. }
  81020. else {
  81021. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81022. }
  81023. // Instances
  81024. if (useInstances) {
  81025. defines.push("#define INSTANCES");
  81026. attribs.push("world0");
  81027. attribs.push("world1");
  81028. attribs.push("world2");
  81029. attribs.push("world3");
  81030. }
  81031. // Get correct effect
  81032. var join = defines.join("\n");
  81033. if (this._cachedDefines !== join) {
  81034. this._cachedDefines = join;
  81035. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  81036. }
  81037. return this._glowMapGenerationEffect.isReady();
  81038. };
  81039. /**
  81040. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  81041. */
  81042. HighlightLayer.prototype.render = function () {
  81043. var currentEffect = this._glowMapMergeEffect;
  81044. // Check
  81045. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  81046. return;
  81047. var engine = this._scene.getEngine();
  81048. this.onBeforeComposeObservable.notifyObservers(this);
  81049. // Render
  81050. engine.enableEffect(currentEffect);
  81051. engine.setState(false);
  81052. // Cache
  81053. var previousStencilBuffer = engine.getStencilBuffer();
  81054. var previousStencilFunction = engine.getStencilFunction();
  81055. var previousStencilMask = engine.getStencilMask();
  81056. var previousStencilOperationPass = engine.getStencilOperationPass();
  81057. var previousStencilOperationFail = engine.getStencilOperationFail();
  81058. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  81059. var previousAlphaMode = engine.getAlphaMode();
  81060. // Texture
  81061. currentEffect.setTexture("textureSampler", this._blurTexture);
  81062. // VBOs
  81063. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  81064. // Stencil operations
  81065. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  81066. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  81067. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  81068. // Draw order
  81069. engine.setAlphaMode(this._options.alphaBlendingMode);
  81070. engine.setStencilMask(0x00);
  81071. engine.setStencilBuffer(true);
  81072. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  81073. if (this.outerGlow) {
  81074. currentEffect.setFloat("offset", 0);
  81075. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  81076. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81077. }
  81078. if (this.innerGlow) {
  81079. currentEffect.setFloat("offset", 1);
  81080. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  81081. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81082. }
  81083. // Restore Cache
  81084. engine.setStencilFunction(previousStencilFunction);
  81085. engine.setStencilMask(previousStencilMask);
  81086. engine.setAlphaMode(previousAlphaMode);
  81087. engine.setStencilBuffer(previousStencilBuffer);
  81088. engine.setStencilOperationPass(previousStencilOperationPass);
  81089. engine.setStencilOperationFail(previousStencilOperationFail);
  81090. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  81091. engine._stencilState.reset();
  81092. this.onAfterComposeObservable.notifyObservers(this);
  81093. // Handle size changes.
  81094. var size = this._mainTexture.getSize();
  81095. this.setMainTextureSize();
  81096. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  81097. // Recreate RTT and post processes on size change.
  81098. this.onSizeChangedObservable.notifyObservers(this);
  81099. this.disposeTextureAndPostProcesses();
  81100. this.createTextureAndPostProcesses();
  81101. }
  81102. };
  81103. /**
  81104. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  81105. * @param mesh The mesh to exclude from the highlight layer
  81106. */
  81107. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  81108. if (!this._excludedMeshes) {
  81109. return;
  81110. }
  81111. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  81112. if (!meshExcluded) {
  81113. this._excludedMeshes[mesh.uniqueId] = {
  81114. mesh: mesh,
  81115. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  81116. mesh.getEngine().setStencilBuffer(false);
  81117. }),
  81118. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  81119. mesh.getEngine().setStencilBuffer(true);
  81120. }),
  81121. };
  81122. }
  81123. };
  81124. /**
  81125. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  81126. * @param mesh The mesh to highlight
  81127. */
  81128. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  81129. if (!this._excludedMeshes) {
  81130. return;
  81131. }
  81132. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  81133. if (meshExcluded) {
  81134. if (meshExcluded.beforeRender) {
  81135. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  81136. }
  81137. if (meshExcluded.afterRender) {
  81138. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  81139. }
  81140. }
  81141. this._excludedMeshes[mesh.uniqueId] = null;
  81142. };
  81143. /**
  81144. * Determine if a given mesh will be highlighted by the current HighlightLayer
  81145. * @param mesh mesh to test
  81146. * @returns true if the mesh will be highlighted by the current HighlightLayer
  81147. */
  81148. HighlightLayer.prototype.hasMesh = function (mesh) {
  81149. if (!this._meshes) {
  81150. return false;
  81151. }
  81152. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  81153. };
  81154. /**
  81155. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  81156. * @param mesh The mesh to highlight
  81157. * @param color The color of the highlight
  81158. * @param glowEmissiveOnly Extract the glow from the emissive texture
  81159. */
  81160. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  81161. var _this = this;
  81162. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  81163. if (!this._meshes) {
  81164. return;
  81165. }
  81166. var meshHighlight = this._meshes[mesh.uniqueId];
  81167. if (meshHighlight) {
  81168. meshHighlight.color = color;
  81169. }
  81170. else {
  81171. this._meshes[mesh.uniqueId] = {
  81172. mesh: mesh,
  81173. color: color,
  81174. // Lambda required for capture due to Observable this context
  81175. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  81176. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  81177. _this.defaultStencilReference(mesh);
  81178. }
  81179. else {
  81180. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  81181. }
  81182. }),
  81183. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  81184. glowEmissiveOnly: glowEmissiveOnly
  81185. };
  81186. }
  81187. this._shouldRender = true;
  81188. };
  81189. /**
  81190. * Remove a mesh from the highlight layer in order to make it stop glowing.
  81191. * @param mesh The mesh to highlight
  81192. */
  81193. HighlightLayer.prototype.removeMesh = function (mesh) {
  81194. if (!this._meshes) {
  81195. return;
  81196. }
  81197. var meshHighlight = this._meshes[mesh.uniqueId];
  81198. if (meshHighlight) {
  81199. if (meshHighlight.observerHighlight) {
  81200. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  81201. }
  81202. if (meshHighlight.observerDefault) {
  81203. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  81204. }
  81205. delete this._meshes[mesh.uniqueId];
  81206. }
  81207. this._shouldRender = false;
  81208. for (var meshHighlightToCheck in this._meshes) {
  81209. if (this._meshes[meshHighlightToCheck]) {
  81210. this._shouldRender = true;
  81211. break;
  81212. }
  81213. }
  81214. };
  81215. /**
  81216. * Returns true if the layer contains information to display, otherwise false.
  81217. */
  81218. HighlightLayer.prototype.shouldRender = function () {
  81219. return this.isEnabled && this._shouldRender;
  81220. };
  81221. /**
  81222. * Sets the main texture desired size which is the closest power of two
  81223. * of the engine canvas size.
  81224. */
  81225. HighlightLayer.prototype.setMainTextureSize = function () {
  81226. if (this._options.mainTextureFixedSize) {
  81227. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  81228. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  81229. }
  81230. else {
  81231. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  81232. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  81233. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  81234. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  81235. }
  81236. };
  81237. /**
  81238. * Force the stencil to the normal expected value for none glowing parts
  81239. */
  81240. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  81241. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  81242. };
  81243. /**
  81244. * Dispose only the render target textures and post process.
  81245. */
  81246. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  81247. this._blurTexture.dispose();
  81248. this._mainTexture.dispose();
  81249. this._downSamplePostprocess.dispose();
  81250. this._horizontalBlurPostprocess.dispose();
  81251. this._verticalBlurPostprocess.dispose();
  81252. };
  81253. /**
  81254. * Dispose the highlight layer and free resources.
  81255. */
  81256. HighlightLayer.prototype.dispose = function () {
  81257. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81258. if (vertexBuffer) {
  81259. vertexBuffer.dispose();
  81260. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81261. }
  81262. if (this._indexBuffer) {
  81263. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81264. this._indexBuffer = null;
  81265. }
  81266. // Clean textures and post processes
  81267. this.disposeTextureAndPostProcesses();
  81268. if (this._meshes) {
  81269. // Clean mesh references
  81270. for (var id in this._meshes) {
  81271. var meshHighlight = this._meshes[id];
  81272. if (meshHighlight && meshHighlight.mesh) {
  81273. if (meshHighlight.observerHighlight) {
  81274. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  81275. }
  81276. if (meshHighlight.observerDefault) {
  81277. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  81278. }
  81279. }
  81280. }
  81281. this._meshes = null;
  81282. }
  81283. if (this._excludedMeshes) {
  81284. for (var id in this._excludedMeshes) {
  81285. var meshHighlight = this._excludedMeshes[id];
  81286. if (meshHighlight) {
  81287. if (meshHighlight.beforeRender) {
  81288. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  81289. }
  81290. if (meshHighlight.afterRender) {
  81291. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  81292. }
  81293. }
  81294. }
  81295. this._excludedMeshes = null;
  81296. }
  81297. // Remove from scene
  81298. var index = this._scene.highlightLayers.indexOf(this, 0);
  81299. if (index > -1) {
  81300. this._scene.highlightLayers.splice(index, 1);
  81301. }
  81302. // Callback
  81303. this.onDisposeObservable.notifyObservers(this);
  81304. this.onDisposeObservable.clear();
  81305. this.onBeforeRenderMainTextureObservable.clear();
  81306. this.onBeforeBlurObservable.clear();
  81307. this.onBeforeComposeObservable.clear();
  81308. this.onAfterComposeObservable.clear();
  81309. this.onSizeChangedObservable.clear();
  81310. };
  81311. /**
  81312. * The neutral color used during the preparation of the glow effect.
  81313. * This is black by default as the blend operation is a blend operation.
  81314. */
  81315. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  81316. /**
  81317. * Stencil value used for glowing meshes.
  81318. */
  81319. HighlightLayer.glowingMeshStencilReference = 0x02;
  81320. /**
  81321. * Stencil value used for the other meshes in the scene.
  81322. */
  81323. HighlightLayer.normalMeshStencilReference = 0x01;
  81324. return HighlightLayer;
  81325. }());
  81326. BABYLON.HighlightLayer = HighlightLayer;
  81327. })(BABYLON || (BABYLON = {}));
  81328. //# sourceMappingURL=babylon.highlightlayer.js.map
  81329. var BABYLON;
  81330. (function (BABYLON) {
  81331. /**
  81332. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  81333. */
  81334. var AssetTaskState;
  81335. (function (AssetTaskState) {
  81336. /**
  81337. * Initialization
  81338. */
  81339. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  81340. /**
  81341. * Running
  81342. */
  81343. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  81344. /**
  81345. * Done
  81346. */
  81347. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  81348. /**
  81349. * Error
  81350. */
  81351. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  81352. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  81353. /**
  81354. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  81355. */
  81356. var AbstractAssetTask = /** @class */ (function () {
  81357. /**
  81358. * Creates a new {BABYLON.AssetsManager}
  81359. * @param name defines the name of the task
  81360. */
  81361. function AbstractAssetTask(
  81362. /**
  81363. * Task name
  81364. */ name) {
  81365. this.name = name;
  81366. this._isCompleted = false;
  81367. this._taskState = AssetTaskState.INIT;
  81368. }
  81369. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  81370. /**
  81371. * Get if the task is completed
  81372. */
  81373. get: function () {
  81374. return this._isCompleted;
  81375. },
  81376. enumerable: true,
  81377. configurable: true
  81378. });
  81379. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  81380. /**
  81381. * Gets the current state of the task
  81382. */
  81383. get: function () {
  81384. return this._taskState;
  81385. },
  81386. enumerable: true,
  81387. configurable: true
  81388. });
  81389. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  81390. /**
  81391. * Gets the current error object (if task is in error)
  81392. */
  81393. get: function () {
  81394. return this._errorObject;
  81395. },
  81396. enumerable: true,
  81397. configurable: true
  81398. });
  81399. /**
  81400. * Internal only
  81401. * @ignore
  81402. */
  81403. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  81404. if (this._errorObject) {
  81405. return;
  81406. }
  81407. this._errorObject = {
  81408. message: message,
  81409. exception: exception
  81410. };
  81411. };
  81412. /**
  81413. * Execute the current task
  81414. * @param scene defines the scene where you want your assets to be loaded
  81415. * @param onSuccess is a callback called when the task is successfully executed
  81416. * @param onError is a callback called if an error occurs
  81417. */
  81418. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  81419. var _this = this;
  81420. this._taskState = AssetTaskState.RUNNING;
  81421. this.runTask(scene, function () {
  81422. _this.onDoneCallback(onSuccess, onError);
  81423. }, function (msg, exception) {
  81424. _this.onErrorCallback(onError, msg, exception);
  81425. });
  81426. };
  81427. /**
  81428. * Execute the current task
  81429. * @param scene defines the scene where you want your assets to be loaded
  81430. * @param onSuccess is a callback called when the task is successfully executed
  81431. * @param onError is a callback called if an error occurs
  81432. */
  81433. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81434. throw new Error("runTask is not implemented");
  81435. };
  81436. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  81437. this._taskState = AssetTaskState.ERROR;
  81438. this._errorObject = {
  81439. message: message,
  81440. exception: exception
  81441. };
  81442. if (this.onError) {
  81443. this.onError(this, message, exception);
  81444. }
  81445. onError();
  81446. };
  81447. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  81448. try {
  81449. this._taskState = AssetTaskState.DONE;
  81450. this._isCompleted = true;
  81451. if (this.onSuccess) {
  81452. this.onSuccess(this);
  81453. }
  81454. onSuccess();
  81455. }
  81456. catch (e) {
  81457. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  81458. }
  81459. };
  81460. return AbstractAssetTask;
  81461. }());
  81462. BABYLON.AbstractAssetTask = AbstractAssetTask;
  81463. /**
  81464. * Class used to share progress information about assets loading
  81465. */
  81466. var AssetsProgressEvent = /** @class */ (function () {
  81467. /**
  81468. * Creates a {BABYLON.AssetsProgressEvent}
  81469. * @param remainingCount defines the number of remaining tasks to process
  81470. * @param totalCount defines the total number of tasks
  81471. * @param task defines the task that was just processed
  81472. */
  81473. function AssetsProgressEvent(remainingCount, totalCount, task) {
  81474. this.remainingCount = remainingCount;
  81475. this.totalCount = totalCount;
  81476. this.task = task;
  81477. }
  81478. return AssetsProgressEvent;
  81479. }());
  81480. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  81481. /**
  81482. * Define a task used by {BABYLON.AssetsManager} to load meshes
  81483. */
  81484. var MeshAssetTask = /** @class */ (function (_super) {
  81485. __extends(MeshAssetTask, _super);
  81486. /**
  81487. * Creates a new {BABYLON.MeshAssetTask}
  81488. * @param name defines the name of the task
  81489. * @param meshesNames defines the list of mesh's names you want to load
  81490. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  81491. * @param sceneFilename defines the filename of the scene to load from
  81492. */
  81493. function MeshAssetTask(
  81494. /**
  81495. * Defines the name of the task
  81496. */
  81497. name,
  81498. /**
  81499. * Defines the list of mesh's names you want to load
  81500. */
  81501. meshesNames,
  81502. /**
  81503. * Defines the root url to use as a base to load your meshes and associated resources
  81504. */
  81505. rootUrl,
  81506. /**
  81507. * Defines the filename of the scene to load from
  81508. */
  81509. sceneFilename) {
  81510. var _this = _super.call(this, name) || this;
  81511. _this.name = name;
  81512. _this.meshesNames = meshesNames;
  81513. _this.rootUrl = rootUrl;
  81514. _this.sceneFilename = sceneFilename;
  81515. return _this;
  81516. }
  81517. /**
  81518. * Execute the current task
  81519. * @param scene defines the scene where you want your assets to be loaded
  81520. * @param onSuccess is a callback called when the task is successfully executed
  81521. * @param onError is a callback called if an error occurs
  81522. */
  81523. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81524. var _this = this;
  81525. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  81526. _this.loadedMeshes = meshes;
  81527. _this.loadedParticleSystems = particleSystems;
  81528. _this.loadedSkeletons = skeletons;
  81529. onSuccess();
  81530. }, null, function (scene, message, exception) {
  81531. onError(message, exception);
  81532. });
  81533. };
  81534. return MeshAssetTask;
  81535. }(AbstractAssetTask));
  81536. BABYLON.MeshAssetTask = MeshAssetTask;
  81537. /**
  81538. * Define a task used by {BABYLON.AssetsManager} to load text content
  81539. */
  81540. var TextFileAssetTask = /** @class */ (function (_super) {
  81541. __extends(TextFileAssetTask, _super);
  81542. /**
  81543. * Creates a new TextFileAssetTask object
  81544. * @param name defines the name of the task
  81545. * @param url defines the location of the file to load
  81546. */
  81547. function TextFileAssetTask(
  81548. /**
  81549. * Defines the name of the task
  81550. */
  81551. name,
  81552. /**
  81553. * Defines the location of the file to load
  81554. */
  81555. url) {
  81556. var _this = _super.call(this, name) || this;
  81557. _this.name = name;
  81558. _this.url = url;
  81559. return _this;
  81560. }
  81561. /**
  81562. * Execute the current task
  81563. * @param scene defines the scene where you want your assets to be loaded
  81564. * @param onSuccess is a callback called when the task is successfully executed
  81565. * @param onError is a callback called if an error occurs
  81566. */
  81567. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81568. var _this = this;
  81569. scene._loadFile(this.url, function (data) {
  81570. _this.text = data;
  81571. onSuccess();
  81572. }, undefined, false, true, function (request, exception) {
  81573. if (request) {
  81574. onError(request.status + " " + request.statusText, exception);
  81575. }
  81576. });
  81577. };
  81578. return TextFileAssetTask;
  81579. }(AbstractAssetTask));
  81580. BABYLON.TextFileAssetTask = TextFileAssetTask;
  81581. /**
  81582. * Define a task used by {BABYLON.AssetsManager} to load binary data
  81583. */
  81584. var BinaryFileAssetTask = /** @class */ (function (_super) {
  81585. __extends(BinaryFileAssetTask, _super);
  81586. /**
  81587. * Creates a new BinaryFileAssetTask object
  81588. * @param name defines the name of the new task
  81589. * @param url defines the location of the file to load
  81590. */
  81591. function BinaryFileAssetTask(
  81592. /**
  81593. * Defines the name of the task
  81594. */
  81595. name,
  81596. /**
  81597. * Defines the location of the file to load
  81598. */
  81599. url) {
  81600. var _this = _super.call(this, name) || this;
  81601. _this.name = name;
  81602. _this.url = url;
  81603. return _this;
  81604. }
  81605. /**
  81606. * Execute the current task
  81607. * @param scene defines the scene where you want your assets to be loaded
  81608. * @param onSuccess is a callback called when the task is successfully executed
  81609. * @param onError is a callback called if an error occurs
  81610. */
  81611. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81612. var _this = this;
  81613. scene._loadFile(this.url, function (data) {
  81614. _this.data = data;
  81615. onSuccess();
  81616. }, undefined, true, true, function (request, exception) {
  81617. if (request) {
  81618. onError(request.status + " " + request.statusText, exception);
  81619. }
  81620. });
  81621. };
  81622. return BinaryFileAssetTask;
  81623. }(AbstractAssetTask));
  81624. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  81625. /**
  81626. * Define a task used by {BABYLON.AssetsManager} to load images
  81627. */
  81628. var ImageAssetTask = /** @class */ (function (_super) {
  81629. __extends(ImageAssetTask, _super);
  81630. /**
  81631. * Creates a new ImageAssetTask
  81632. * @param name defines the name of the task
  81633. * @param url defines the location of the image to load
  81634. */
  81635. function ImageAssetTask(
  81636. /**
  81637. * Defines the name of the task
  81638. */
  81639. name,
  81640. /**
  81641. * Defines the location of the image to load
  81642. */
  81643. url) {
  81644. var _this = _super.call(this, name) || this;
  81645. _this.name = name;
  81646. _this.url = url;
  81647. return _this;
  81648. }
  81649. /**
  81650. * Execute the current task
  81651. * @param scene defines the scene where you want your assets to be loaded
  81652. * @param onSuccess is a callback called when the task is successfully executed
  81653. * @param onError is a callback called if an error occurs
  81654. */
  81655. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81656. var _this = this;
  81657. var img = new Image();
  81658. BABYLON.Tools.SetCorsBehavior(this.url, img);
  81659. img.onload = function () {
  81660. _this.image = img;
  81661. onSuccess();
  81662. };
  81663. img.onerror = function (err) {
  81664. onError("Error loading image", err);
  81665. };
  81666. img.src = this.url;
  81667. };
  81668. return ImageAssetTask;
  81669. }(AbstractAssetTask));
  81670. BABYLON.ImageAssetTask = ImageAssetTask;
  81671. /**
  81672. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  81673. */
  81674. var TextureAssetTask = /** @class */ (function (_super) {
  81675. __extends(TextureAssetTask, _super);
  81676. /**
  81677. * Creates a new TextureAssetTask object
  81678. * @param name defines the name of the task
  81679. * @param url defines the location of the file to load
  81680. * @param noMipmap defines if mipmap should not be generated (default is false)
  81681. * @param invertY defines if texture must be inverted on Y axis (default is false)
  81682. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  81683. */
  81684. function TextureAssetTask(
  81685. /**
  81686. * Defines the name of the task
  81687. */
  81688. name,
  81689. /**
  81690. * Defines the location of the file to load
  81691. */
  81692. url,
  81693. /**
  81694. * Defines if mipmap should not be generated (default is false)
  81695. */
  81696. noMipmap,
  81697. /**
  81698. * Defines if texture must be inverted on Y axis (default is false)
  81699. */
  81700. invertY,
  81701. /**
  81702. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  81703. */
  81704. samplingMode) {
  81705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81706. var _this = _super.call(this, name) || this;
  81707. _this.name = name;
  81708. _this.url = url;
  81709. _this.noMipmap = noMipmap;
  81710. _this.invertY = invertY;
  81711. _this.samplingMode = samplingMode;
  81712. return _this;
  81713. }
  81714. /**
  81715. * Execute the current task
  81716. * @param scene defines the scene where you want your assets to be loaded
  81717. * @param onSuccess is a callback called when the task is successfully executed
  81718. * @param onError is a callback called if an error occurs
  81719. */
  81720. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81721. var onload = function () {
  81722. onSuccess();
  81723. };
  81724. var onerror = function (message, exception) {
  81725. onError(message, exception);
  81726. };
  81727. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  81728. };
  81729. return TextureAssetTask;
  81730. }(AbstractAssetTask));
  81731. BABYLON.TextureAssetTask = TextureAssetTask;
  81732. /**
  81733. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  81734. */
  81735. var CubeTextureAssetTask = /** @class */ (function (_super) {
  81736. __extends(CubeTextureAssetTask, _super);
  81737. /**
  81738. * Creates a new CubeTextureAssetTask
  81739. * @param name defines the name of the task
  81740. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81741. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81742. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81743. * @param files defines the explicit list of files (undefined by default)
  81744. */
  81745. function CubeTextureAssetTask(
  81746. /**
  81747. * Defines the name of the task
  81748. */
  81749. name,
  81750. /**
  81751. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81752. */
  81753. url,
  81754. /**
  81755. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81756. */
  81757. extensions,
  81758. /**
  81759. * Defines if mipmaps should not be generated (default is false)
  81760. */
  81761. noMipmap,
  81762. /**
  81763. * Defines the explicit list of files (undefined by default)
  81764. */
  81765. files) {
  81766. var _this = _super.call(this, name) || this;
  81767. _this.name = name;
  81768. _this.url = url;
  81769. _this.extensions = extensions;
  81770. _this.noMipmap = noMipmap;
  81771. _this.files = files;
  81772. return _this;
  81773. }
  81774. /**
  81775. * Execute the current task
  81776. * @param scene defines the scene where you want your assets to be loaded
  81777. * @param onSuccess is a callback called when the task is successfully executed
  81778. * @param onError is a callback called if an error occurs
  81779. */
  81780. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81781. var onload = function () {
  81782. onSuccess();
  81783. };
  81784. var onerror = function (message, exception) {
  81785. onError(message, exception);
  81786. };
  81787. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  81788. };
  81789. return CubeTextureAssetTask;
  81790. }(AbstractAssetTask));
  81791. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  81792. /**
  81793. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  81794. */
  81795. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  81796. __extends(HDRCubeTextureAssetTask, _super);
  81797. /**
  81798. * Creates a new HDRCubeTextureAssetTask object
  81799. * @param name defines the name of the task
  81800. * @param url defines the location of the file to load
  81801. * @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.
  81802. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81803. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81804. * @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)
  81805. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81806. */
  81807. function HDRCubeTextureAssetTask(
  81808. /**
  81809. * Defines the name of the task
  81810. */
  81811. name,
  81812. /**
  81813. * Defines the location of the file to load
  81814. */
  81815. url,
  81816. /**
  81817. * 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.
  81818. */
  81819. size,
  81820. /**
  81821. * Defines if mipmaps should not be generated (default is false)
  81822. */
  81823. noMipmap,
  81824. /**
  81825. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81826. */
  81827. generateHarmonics,
  81828. /**
  81829. * 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)
  81830. */
  81831. useInGammaSpace,
  81832. /**
  81833. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81834. */
  81835. usePMREMGenerator) {
  81836. if (noMipmap === void 0) { noMipmap = false; }
  81837. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81838. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81839. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81840. var _this = _super.call(this, name) || this;
  81841. _this.name = name;
  81842. _this.url = url;
  81843. _this.size = size;
  81844. _this.noMipmap = noMipmap;
  81845. _this.generateHarmonics = generateHarmonics;
  81846. _this.useInGammaSpace = useInGammaSpace;
  81847. _this.usePMREMGenerator = usePMREMGenerator;
  81848. return _this;
  81849. }
  81850. /**
  81851. * Execute the current task
  81852. * @param scene defines the scene where you want your assets to be loaded
  81853. * @param onSuccess is a callback called when the task is successfully executed
  81854. * @param onError is a callback called if an error occurs
  81855. */
  81856. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  81857. var onload = function () {
  81858. onSuccess();
  81859. };
  81860. var onerror = function (message, exception) {
  81861. onError(message, exception);
  81862. };
  81863. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  81864. };
  81865. return HDRCubeTextureAssetTask;
  81866. }(AbstractAssetTask));
  81867. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  81868. /**
  81869. * This class can be used to easily import assets into a scene
  81870. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  81871. */
  81872. var AssetsManager = /** @class */ (function () {
  81873. /**
  81874. * Creates a new AssetsManager
  81875. * @param scene defines the scene to work on
  81876. */
  81877. function AssetsManager(scene) {
  81878. this._isLoading = false;
  81879. this._tasks = new Array();
  81880. this._waitingTasksCount = 0;
  81881. this._totalTasksCount = 0;
  81882. /**
  81883. * Observable called when all tasks are processed
  81884. */
  81885. this.onTaskSuccessObservable = new BABYLON.Observable();
  81886. /**
  81887. * Observable called when a task had an error
  81888. */
  81889. this.onTaskErrorObservable = new BABYLON.Observable();
  81890. /**
  81891. * Observable called when a task is successful
  81892. */
  81893. this.onTasksDoneObservable = new BABYLON.Observable();
  81894. /**
  81895. * Observable called when a task is done (whatever the result is)
  81896. */
  81897. this.onProgressObservable = new BABYLON.Observable();
  81898. /**
  81899. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  81900. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  81901. */
  81902. this.useDefaultLoadingScreen = true;
  81903. this._scene = scene;
  81904. }
  81905. /**
  81906. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  81907. * @param taskName defines the name of the new task
  81908. * @param meshesNames defines the name of meshes to load
  81909. * @param rootUrl defines the root url to use to locate files
  81910. * @param sceneFilename defines the filename of the scene file
  81911. * @returns a new {BABYLON.MeshAssetTask} object
  81912. */
  81913. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  81914. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  81915. this._tasks.push(task);
  81916. return task;
  81917. };
  81918. /**
  81919. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  81920. * @param taskName defines the name of the new task
  81921. * @param url defines the url of the file to load
  81922. * @returns a new {BABYLON.TextFileAssetTask} object
  81923. */
  81924. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  81925. var task = new TextFileAssetTask(taskName, url);
  81926. this._tasks.push(task);
  81927. return task;
  81928. };
  81929. /**
  81930. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  81931. * @param taskName defines the name of the new task
  81932. * @param url defines the url of the file to load
  81933. * @returns a new {BABYLON.BinaryFileAssetTask} object
  81934. */
  81935. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  81936. var task = new BinaryFileAssetTask(taskName, url);
  81937. this._tasks.push(task);
  81938. return task;
  81939. };
  81940. /**
  81941. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  81942. * @param taskName defines the name of the new task
  81943. * @param url defines the url of the file to load
  81944. * @returns a new {BABYLON.ImageAssetTask} object
  81945. */
  81946. AssetsManager.prototype.addImageTask = function (taskName, url) {
  81947. var task = new ImageAssetTask(taskName, url);
  81948. this._tasks.push(task);
  81949. return task;
  81950. };
  81951. /**
  81952. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  81953. * @param taskName defines the name of the new task
  81954. * @param url defines the url of the file to load
  81955. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81956. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  81957. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  81958. * @returns a new {BABYLON.TextureAssetTask} object
  81959. */
  81960. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  81961. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81962. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  81963. this._tasks.push(task);
  81964. return task;
  81965. };
  81966. /**
  81967. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  81968. * @param taskName defines the name of the new task
  81969. * @param url defines the url of the file to load
  81970. * @param extensions defines the extension to use to load the cube map (can be null)
  81971. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81972. * @param files defines the list of files to load (can be null)
  81973. * @returns a new {BABYLON.CubeTextureAssetTask} object
  81974. */
  81975. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  81976. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  81977. this._tasks.push(task);
  81978. return task;
  81979. };
  81980. /**
  81981. *
  81982. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  81983. * @param taskName defines the name of the new task
  81984. * @param url defines the url of the file to load
  81985. * @param size defines the size you want for the cubemap (can be null)
  81986. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81987. * @param generateHarmonics defines if you want to automatically generate (true by default)
  81988. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  81989. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  81990. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  81991. */
  81992. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  81993. if (noMipmap === void 0) { noMipmap = false; }
  81994. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81995. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81996. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81997. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  81998. this._tasks.push(task);
  81999. return task;
  82000. };
  82001. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  82002. var _this = this;
  82003. this._waitingTasksCount--;
  82004. try {
  82005. if (task.taskState === AssetTaskState.DONE) {
  82006. // Let's remove successfull tasks
  82007. BABYLON.Tools.SetImmediate(function () {
  82008. var index = _this._tasks.indexOf(task);
  82009. if (index > -1) {
  82010. _this._tasks.splice(index, 1);
  82011. }
  82012. });
  82013. }
  82014. if (this.onProgress) {
  82015. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  82016. }
  82017. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  82018. }
  82019. catch (e) {
  82020. BABYLON.Tools.Error("Error running progress callbacks.");
  82021. console.log(e);
  82022. }
  82023. if (this._waitingTasksCount === 0) {
  82024. try {
  82025. if (this.onFinish) {
  82026. this.onFinish(this._tasks);
  82027. }
  82028. this.onTasksDoneObservable.notifyObservers(this._tasks);
  82029. }
  82030. catch (e) {
  82031. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  82032. console.log(e);
  82033. }
  82034. this._isLoading = false;
  82035. this._scene.getEngine().hideLoadingUI();
  82036. }
  82037. };
  82038. AssetsManager.prototype._runTask = function (task) {
  82039. var _this = this;
  82040. var done = function () {
  82041. try {
  82042. if (_this.onTaskSuccess) {
  82043. _this.onTaskSuccess(task);
  82044. }
  82045. _this.onTaskSuccessObservable.notifyObservers(task);
  82046. _this._decreaseWaitingTasksCount(task);
  82047. }
  82048. catch (e) {
  82049. error("Error executing task success callbacks", e);
  82050. }
  82051. };
  82052. var error = function (message, exception) {
  82053. task._setErrorObject(message, exception);
  82054. if (_this.onTaskError) {
  82055. _this.onTaskError(task);
  82056. }
  82057. _this.onTaskErrorObservable.notifyObservers(task);
  82058. _this._decreaseWaitingTasksCount(task);
  82059. };
  82060. task.run(this._scene, done, error);
  82061. };
  82062. /**
  82063. * Reset the {BABYLON.AssetsManager} and remove all tasks
  82064. * @return the current instance of the {BABYLON.AssetsManager}
  82065. */
  82066. AssetsManager.prototype.reset = function () {
  82067. this._isLoading = false;
  82068. this._tasks = new Array();
  82069. return this;
  82070. };
  82071. /**
  82072. * Start the loading process
  82073. * @return the current instance of the {BABYLON.AssetsManager}
  82074. */
  82075. AssetsManager.prototype.load = function () {
  82076. if (this._isLoading) {
  82077. return this;
  82078. }
  82079. this._isLoading = true;
  82080. this._waitingTasksCount = this._tasks.length;
  82081. this._totalTasksCount = this._tasks.length;
  82082. if (this._waitingTasksCount === 0) {
  82083. if (this.onFinish) {
  82084. this.onFinish(this._tasks);
  82085. }
  82086. this.onTasksDoneObservable.notifyObservers(this._tasks);
  82087. return this;
  82088. }
  82089. if (this.useDefaultLoadingScreen) {
  82090. this._scene.getEngine().displayLoadingUI();
  82091. }
  82092. for (var index = 0; index < this._tasks.length; index++) {
  82093. var task = this._tasks[index];
  82094. this._runTask(task);
  82095. }
  82096. return this;
  82097. };
  82098. return AssetsManager;
  82099. }());
  82100. BABYLON.AssetsManager = AssetsManager;
  82101. })(BABYLON || (BABYLON = {}));
  82102. //# sourceMappingURL=babylon.assetsManager.js.map
  82103. var BABYLON;
  82104. (function (BABYLON) {
  82105. var serializedGeometries = [];
  82106. var serializeGeometry = function (geometry, serializationGeometries) {
  82107. if (serializedGeometries[geometry.id]) {
  82108. return;
  82109. }
  82110. if (geometry.doNotSerialize) {
  82111. return;
  82112. }
  82113. if (geometry instanceof BABYLON.BoxGeometry) {
  82114. serializationGeometries.boxes.push(geometry.serialize());
  82115. }
  82116. else if (geometry instanceof BABYLON.SphereGeometry) {
  82117. serializationGeometries.spheres.push(geometry.serialize());
  82118. }
  82119. else if (geometry instanceof BABYLON.CylinderGeometry) {
  82120. serializationGeometries.cylinders.push(geometry.serialize());
  82121. }
  82122. else if (geometry instanceof BABYLON.TorusGeometry) {
  82123. serializationGeometries.toruses.push(geometry.serialize());
  82124. }
  82125. else if (geometry instanceof BABYLON.GroundGeometry) {
  82126. serializationGeometries.grounds.push(geometry.serialize());
  82127. }
  82128. else if (geometry instanceof BABYLON.Plane) {
  82129. serializationGeometries.planes.push(geometry.serialize());
  82130. }
  82131. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  82132. serializationGeometries.torusKnots.push(geometry.serialize());
  82133. }
  82134. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  82135. throw new Error("Unknown primitive type");
  82136. }
  82137. else {
  82138. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  82139. }
  82140. serializedGeometries[geometry.id] = true;
  82141. };
  82142. var serializeMesh = function (mesh, serializationScene) {
  82143. var serializationObject = {};
  82144. // Geometry
  82145. var geometry = mesh._geometry;
  82146. if (geometry) {
  82147. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  82148. // 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
  82149. serializeGeometry(geometry, serializationScene.geometries);
  82150. }
  82151. }
  82152. // Custom
  82153. if (mesh.serialize) {
  82154. mesh.serialize(serializationObject);
  82155. }
  82156. return serializationObject;
  82157. };
  82158. var finalizeSingleMesh = function (mesh, serializationObject) {
  82159. //only works if the mesh is already loaded
  82160. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  82161. //serialize material
  82162. if (mesh.material) {
  82163. if (mesh.material instanceof BABYLON.StandardMaterial) {
  82164. serializationObject.materials = serializationObject.materials || [];
  82165. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  82166. serializationObject.materials.push(mesh.material.serialize());
  82167. }
  82168. }
  82169. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  82170. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  82171. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  82172. serializationObject.multiMaterials.push(mesh.material.serialize());
  82173. }
  82174. }
  82175. }
  82176. //serialize geometry
  82177. var geometry = mesh._geometry;
  82178. if (geometry) {
  82179. if (!serializationObject.geometries) {
  82180. serializationObject.geometries = {};
  82181. serializationObject.geometries.boxes = [];
  82182. serializationObject.geometries.spheres = [];
  82183. serializationObject.geometries.cylinders = [];
  82184. serializationObject.geometries.toruses = [];
  82185. serializationObject.geometries.grounds = [];
  82186. serializationObject.geometries.planes = [];
  82187. serializationObject.geometries.torusKnots = [];
  82188. serializationObject.geometries.vertexData = [];
  82189. }
  82190. serializeGeometry(geometry, serializationObject.geometries);
  82191. }
  82192. // Skeletons
  82193. if (mesh.skeleton) {
  82194. serializationObject.skeletons = serializationObject.skeletons || [];
  82195. serializationObject.skeletons.push(mesh.skeleton.serialize());
  82196. }
  82197. //serialize the actual mesh
  82198. serializationObject.meshes = serializationObject.meshes || [];
  82199. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  82200. }
  82201. };
  82202. var SceneSerializer = /** @class */ (function () {
  82203. function SceneSerializer() {
  82204. }
  82205. SceneSerializer.ClearCache = function () {
  82206. serializedGeometries = [];
  82207. };
  82208. SceneSerializer.Serialize = function (scene) {
  82209. var serializationObject = {};
  82210. SceneSerializer.ClearCache();
  82211. // Scene
  82212. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  82213. serializationObject.autoClear = scene.autoClear;
  82214. serializationObject.clearColor = scene.clearColor.asArray();
  82215. serializationObject.ambientColor = scene.ambientColor.asArray();
  82216. serializationObject.gravity = scene.gravity.asArray();
  82217. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  82218. serializationObject.workerCollisions = scene.workerCollisions;
  82219. // Fog
  82220. if (scene.fogMode && scene.fogMode !== 0) {
  82221. serializationObject.fogMode = scene.fogMode;
  82222. serializationObject.fogColor = scene.fogColor.asArray();
  82223. serializationObject.fogStart = scene.fogStart;
  82224. serializationObject.fogEnd = scene.fogEnd;
  82225. serializationObject.fogDensity = scene.fogDensity;
  82226. }
  82227. //Physics
  82228. if (scene.isPhysicsEnabled()) {
  82229. var physicEngine = scene.getPhysicsEngine();
  82230. if (physicEngine) {
  82231. serializationObject.physicsEnabled = true;
  82232. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  82233. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  82234. }
  82235. }
  82236. // Metadata
  82237. if (scene.metadata) {
  82238. serializationObject.metadata = scene.metadata;
  82239. }
  82240. // Morph targets
  82241. serializationObject.morphTargetManagers = [];
  82242. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  82243. var abstractMesh = _a[_i];
  82244. var manager = abstractMesh.morphTargetManager;
  82245. if (manager) {
  82246. serializationObject.morphTargetManagers.push(manager.serialize());
  82247. }
  82248. }
  82249. // Lights
  82250. serializationObject.lights = [];
  82251. var index;
  82252. var light;
  82253. for (index = 0; index < scene.lights.length; index++) {
  82254. light = scene.lights[index];
  82255. if (!light.doNotSerialize) {
  82256. serializationObject.lights.push(light.serialize());
  82257. }
  82258. }
  82259. // Cameras
  82260. serializationObject.cameras = [];
  82261. for (index = 0; index < scene.cameras.length; index++) {
  82262. var camera = scene.cameras[index];
  82263. if (!camera.doNotSerialize) {
  82264. serializationObject.cameras.push(camera.serialize());
  82265. }
  82266. }
  82267. if (scene.activeCamera) {
  82268. serializationObject.activeCameraID = scene.activeCamera.id;
  82269. }
  82270. // Animations
  82271. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  82272. // Materials
  82273. serializationObject.materials = [];
  82274. serializationObject.multiMaterials = [];
  82275. var material;
  82276. for (index = 0; index < scene.materials.length; index++) {
  82277. material = scene.materials[index];
  82278. if (!material.doNotSerialize) {
  82279. serializationObject.materials.push(material.serialize());
  82280. }
  82281. }
  82282. // MultiMaterials
  82283. serializationObject.multiMaterials = [];
  82284. for (index = 0; index < scene.multiMaterials.length; index++) {
  82285. var multiMaterial = scene.multiMaterials[index];
  82286. serializationObject.multiMaterials.push(multiMaterial.serialize());
  82287. }
  82288. // Environment texture
  82289. if (scene.environmentTexture) {
  82290. serializationObject.environmentTexture = scene.environmentTexture.name;
  82291. }
  82292. // Skeletons
  82293. serializationObject.skeletons = [];
  82294. for (index = 0; index < scene.skeletons.length; index++) {
  82295. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  82296. }
  82297. // Transform nodes
  82298. serializationObject.transformNodes = [];
  82299. for (index = 0; index < scene.transformNodes.length; index++) {
  82300. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  82301. }
  82302. // Geometries
  82303. serializationObject.geometries = {};
  82304. serializationObject.geometries.boxes = [];
  82305. serializationObject.geometries.spheres = [];
  82306. serializationObject.geometries.cylinders = [];
  82307. serializationObject.geometries.toruses = [];
  82308. serializationObject.geometries.grounds = [];
  82309. serializationObject.geometries.planes = [];
  82310. serializationObject.geometries.torusKnots = [];
  82311. serializationObject.geometries.vertexData = [];
  82312. serializedGeometries = [];
  82313. var geometries = scene.getGeometries();
  82314. for (index = 0; index < geometries.length; index++) {
  82315. var geometry = geometries[index];
  82316. if (geometry.isReady()) {
  82317. serializeGeometry(geometry, serializationObject.geometries);
  82318. }
  82319. }
  82320. // Meshes
  82321. serializationObject.meshes = [];
  82322. for (index = 0; index < scene.meshes.length; index++) {
  82323. var abstractMesh = scene.meshes[index];
  82324. if (abstractMesh instanceof BABYLON.Mesh) {
  82325. var mesh = abstractMesh;
  82326. if (!mesh.doNotSerialize) {
  82327. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  82328. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  82329. }
  82330. }
  82331. }
  82332. }
  82333. // Particles Systems
  82334. serializationObject.particleSystems = [];
  82335. for (index = 0; index < scene.particleSystems.length; index++) {
  82336. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  82337. }
  82338. // Lens flares
  82339. serializationObject.lensFlareSystems = [];
  82340. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  82341. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  82342. }
  82343. // Shadows
  82344. serializationObject.shadowGenerators = [];
  82345. for (index = 0; index < scene.lights.length; index++) {
  82346. light = scene.lights[index];
  82347. var shadowGenerator = light.getShadowGenerator();
  82348. if (shadowGenerator) {
  82349. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  82350. }
  82351. }
  82352. // Action Manager
  82353. if (scene.actionManager) {
  82354. serializationObject.actions = scene.actionManager.serialize("scene");
  82355. }
  82356. // Audio
  82357. serializationObject.sounds = [];
  82358. for (index = 0; index < scene.soundTracks.length; index++) {
  82359. var soundtrack = scene.soundTracks[index];
  82360. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  82361. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  82362. }
  82363. }
  82364. return serializationObject;
  82365. };
  82366. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  82367. if (withParents === void 0) { withParents = false; }
  82368. if (withChildren === void 0) { withChildren = false; }
  82369. var serializationObject = {};
  82370. SceneSerializer.ClearCache();
  82371. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  82372. if (withParents || withChildren) {
  82373. //deliberate for loop! not for each, appended should be processed as well.
  82374. for (var i = 0; i < toSerialize.length; ++i) {
  82375. if (withChildren) {
  82376. toSerialize[i].getDescendants().forEach(function (node) {
  82377. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  82378. toSerialize.push(node);
  82379. }
  82380. });
  82381. }
  82382. //make sure the array doesn't contain the object already
  82383. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  82384. toSerialize.push(toSerialize[i].parent);
  82385. }
  82386. }
  82387. }
  82388. toSerialize.forEach(function (mesh) {
  82389. finalizeSingleMesh(mesh, serializationObject);
  82390. });
  82391. return serializationObject;
  82392. };
  82393. return SceneSerializer;
  82394. }());
  82395. BABYLON.SceneSerializer = SceneSerializer;
  82396. })(BABYLON || (BABYLON = {}));
  82397. //# sourceMappingURL=babylon.sceneSerializer.js.map
  82398. var BABYLON;
  82399. (function (BABYLON) {
  82400. var ReflectionProbe = /** @class */ (function () {
  82401. function ReflectionProbe(name, size, scene, generateMipMaps) {
  82402. if (generateMipMaps === void 0) { generateMipMaps = true; }
  82403. var _this = this;
  82404. this.name = name;
  82405. this._viewMatrix = BABYLON.Matrix.Identity();
  82406. this._target = BABYLON.Vector3.Zero();
  82407. this._add = BABYLON.Vector3.Zero();
  82408. this.invertYAxis = false;
  82409. this.position = BABYLON.Vector3.Zero();
  82410. this._scene = scene;
  82411. this._scene.reflectionProbes.push(this);
  82412. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  82413. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  82414. switch (faceIndex) {
  82415. case 0:
  82416. _this._add.copyFromFloats(1, 0, 0);
  82417. break;
  82418. case 1:
  82419. _this._add.copyFromFloats(-1, 0, 0);
  82420. break;
  82421. case 2:
  82422. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  82423. break;
  82424. case 3:
  82425. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  82426. break;
  82427. case 4:
  82428. _this._add.copyFromFloats(0, 0, 1);
  82429. break;
  82430. case 5:
  82431. _this._add.copyFromFloats(0, 0, -1);
  82432. break;
  82433. }
  82434. if (_this._attachedMesh) {
  82435. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  82436. }
  82437. _this.position.addToRef(_this._add, _this._target);
  82438. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  82439. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  82440. scene._forcedViewPosition = _this.position;
  82441. });
  82442. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  82443. scene._forcedViewPosition = null;
  82444. scene.updateTransformMatrix(true);
  82445. });
  82446. if (scene.activeCamera) {
  82447. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  82448. }
  82449. }
  82450. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  82451. get: function () {
  82452. return this._renderTargetTexture.samples;
  82453. },
  82454. set: function (value) {
  82455. this._renderTargetTexture.samples = value;
  82456. },
  82457. enumerable: true,
  82458. configurable: true
  82459. });
  82460. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  82461. get: function () {
  82462. return this._renderTargetTexture.refreshRate;
  82463. },
  82464. set: function (value) {
  82465. this._renderTargetTexture.refreshRate = value;
  82466. },
  82467. enumerable: true,
  82468. configurable: true
  82469. });
  82470. ReflectionProbe.prototype.getScene = function () {
  82471. return this._scene;
  82472. };
  82473. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  82474. get: function () {
  82475. return this._renderTargetTexture;
  82476. },
  82477. enumerable: true,
  82478. configurable: true
  82479. });
  82480. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  82481. get: function () {
  82482. return this._renderTargetTexture.renderList;
  82483. },
  82484. enumerable: true,
  82485. configurable: true
  82486. });
  82487. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  82488. this._attachedMesh = mesh;
  82489. };
  82490. /**
  82491. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  82492. *
  82493. * @param renderingGroupId The rendering group id corresponding to its index
  82494. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  82495. */
  82496. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  82497. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  82498. };
  82499. ReflectionProbe.prototype.dispose = function () {
  82500. var index = this._scene.reflectionProbes.indexOf(this);
  82501. if (index !== -1) {
  82502. // Remove from the scene if found
  82503. this._scene.reflectionProbes.splice(index, 1);
  82504. }
  82505. if (this._renderTargetTexture) {
  82506. this._renderTargetTexture.dispose();
  82507. this._renderTargetTexture = null;
  82508. }
  82509. };
  82510. return ReflectionProbe;
  82511. }());
  82512. BABYLON.ReflectionProbe = ReflectionProbe;
  82513. })(BABYLON || (BABYLON = {}));
  82514. //# sourceMappingURL=babylon.reflectionProbe.js.map
  82515. var BABYLON;
  82516. (function (BABYLON) {
  82517. var Layer = /** @class */ (function () {
  82518. function Layer(name, imgUrl, scene, isBackground, color) {
  82519. this.name = name;
  82520. this.scale = new BABYLON.Vector2(1, 1);
  82521. this.offset = new BABYLON.Vector2(0, 0);
  82522. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  82523. this.layerMask = 0x0FFFFFFF;
  82524. this._vertexBuffers = {};
  82525. // Events
  82526. /**
  82527. * An event triggered when the layer is disposed.
  82528. * @type {BABYLON.Observable}
  82529. */
  82530. this.onDisposeObservable = new BABYLON.Observable();
  82531. /**
  82532. * An event triggered before rendering the scene
  82533. * @type {BABYLON.Observable}
  82534. */
  82535. this.onBeforeRenderObservable = new BABYLON.Observable();
  82536. /**
  82537. * An event triggered after rendering the scene
  82538. * @type {BABYLON.Observable}
  82539. */
  82540. this.onAfterRenderObservable = new BABYLON.Observable();
  82541. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  82542. this.isBackground = isBackground === undefined ? true : isBackground;
  82543. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  82544. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  82545. this._scene.layers.push(this);
  82546. var engine = this._scene.getEngine();
  82547. // VBO
  82548. var vertices = [];
  82549. vertices.push(1, 1);
  82550. vertices.push(-1, 1);
  82551. vertices.push(-1, -1);
  82552. vertices.push(1, -1);
  82553. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82554. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82555. this._createIndexBuffer();
  82556. // Effects
  82557. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  82558. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  82559. }
  82560. Object.defineProperty(Layer.prototype, "onDispose", {
  82561. set: function (callback) {
  82562. if (this._onDisposeObserver) {
  82563. this.onDisposeObservable.remove(this._onDisposeObserver);
  82564. }
  82565. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  82566. },
  82567. enumerable: true,
  82568. configurable: true
  82569. });
  82570. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  82571. set: function (callback) {
  82572. if (this._onBeforeRenderObserver) {
  82573. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  82574. }
  82575. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  82576. },
  82577. enumerable: true,
  82578. configurable: true
  82579. });
  82580. Object.defineProperty(Layer.prototype, "onAfterRender", {
  82581. set: function (callback) {
  82582. if (this._onAfterRenderObserver) {
  82583. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  82584. }
  82585. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  82586. },
  82587. enumerable: true,
  82588. configurable: true
  82589. });
  82590. Layer.prototype._createIndexBuffer = function () {
  82591. var engine = this._scene.getEngine();
  82592. // Indices
  82593. var indices = [];
  82594. indices.push(0);
  82595. indices.push(1);
  82596. indices.push(2);
  82597. indices.push(0);
  82598. indices.push(2);
  82599. indices.push(3);
  82600. this._indexBuffer = engine.createIndexBuffer(indices);
  82601. };
  82602. Layer.prototype._rebuild = function () {
  82603. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82604. if (vb) {
  82605. vb._rebuild();
  82606. }
  82607. this._createIndexBuffer();
  82608. };
  82609. Layer.prototype.render = function () {
  82610. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  82611. // Check
  82612. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  82613. return;
  82614. var engine = this._scene.getEngine();
  82615. this.onBeforeRenderObservable.notifyObservers(this);
  82616. // Render
  82617. engine.enableEffect(currentEffect);
  82618. engine.setState(false);
  82619. // Texture
  82620. currentEffect.setTexture("textureSampler", this.texture);
  82621. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  82622. // Color
  82623. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  82624. // Scale / offset
  82625. currentEffect.setVector2("offset", this.offset);
  82626. currentEffect.setVector2("scale", this.scale);
  82627. // VBOs
  82628. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82629. // Draw order
  82630. if (!this.alphaTest) {
  82631. engine.setAlphaMode(this.alphaBlendingMode);
  82632. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82633. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82634. }
  82635. else {
  82636. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82637. }
  82638. this.onAfterRenderObservable.notifyObservers(this);
  82639. };
  82640. Layer.prototype.dispose = function () {
  82641. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82642. if (vertexBuffer) {
  82643. vertexBuffer.dispose();
  82644. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82645. }
  82646. if (this._indexBuffer) {
  82647. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82648. this._indexBuffer = null;
  82649. }
  82650. if (this.texture) {
  82651. this.texture.dispose();
  82652. this.texture = null;
  82653. }
  82654. // Remove from scene
  82655. var index = this._scene.layers.indexOf(this);
  82656. this._scene.layers.splice(index, 1);
  82657. // Callback
  82658. this.onDisposeObservable.notifyObservers(this);
  82659. this.onDisposeObservable.clear();
  82660. this.onAfterRenderObservable.clear();
  82661. this.onBeforeRenderObservable.clear();
  82662. };
  82663. return Layer;
  82664. }());
  82665. BABYLON.Layer = Layer;
  82666. })(BABYLON || (BABYLON = {}));
  82667. //# sourceMappingURL=babylon.layer.js.map
  82668. var BABYLON;
  82669. (function (BABYLON) {
  82670. var TextureTools = /** @class */ (function () {
  82671. function TextureTools() {
  82672. }
  82673. /**
  82674. * Uses the GPU to create a copy texture rescaled at a given size
  82675. * @param texture Texture to copy from
  82676. * @param width Desired width
  82677. * @param height Desired height
  82678. * @return Generated texture
  82679. */
  82680. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  82681. if (useBilinearMode === void 0) { useBilinearMode = true; }
  82682. var scene = texture.getScene();
  82683. var engine = scene.getEngine();
  82684. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  82685. rtt.wrapU = texture.wrapU;
  82686. rtt.wrapV = texture.wrapV;
  82687. rtt.uOffset = texture.uOffset;
  82688. rtt.vOffset = texture.vOffset;
  82689. rtt.uScale = texture.uScale;
  82690. rtt.vScale = texture.vScale;
  82691. rtt.uAng = texture.uAng;
  82692. rtt.vAng = texture.vAng;
  82693. rtt.wAng = texture.wAng;
  82694. rtt.coordinatesIndex = texture.coordinatesIndex;
  82695. rtt.level = texture.level;
  82696. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  82697. rtt._texture.isReady = false;
  82698. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82699. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82700. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82701. passPostProcess.getEffect().executeWhenCompiled(function () {
  82702. passPostProcess.onApply = function (effect) {
  82703. effect.setTexture("textureSampler", texture);
  82704. };
  82705. var internalTexture = rtt.getInternalTexture();
  82706. if (internalTexture) {
  82707. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  82708. engine.unBindFramebuffer(internalTexture);
  82709. rtt.disposeFramebufferObjects();
  82710. passPostProcess.dispose();
  82711. internalTexture.isReady = true;
  82712. }
  82713. });
  82714. return rtt;
  82715. };
  82716. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  82717. if (!scene._environmentBRDFTexture) {
  82718. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82719. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82720. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82721. scene._environmentBRDFTexture = texture;
  82722. }
  82723. return scene._environmentBRDFTexture;
  82724. };
  82725. 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=";
  82726. return TextureTools;
  82727. }());
  82728. BABYLON.TextureTools = TextureTools;
  82729. })(BABYLON || (BABYLON = {}));
  82730. //# sourceMappingURL=babylon.textureTools.js.map
  82731. var BABYLON;
  82732. (function (BABYLON) {
  82733. var FramingBehavior = /** @class */ (function () {
  82734. function FramingBehavior() {
  82735. this._mode = FramingBehavior.FitFrustumSidesMode;
  82736. this._radiusScale = 1.0;
  82737. this._positionScale = 0.5;
  82738. this._defaultElevation = 0.3;
  82739. this._elevationReturnTime = 1500;
  82740. this._elevationReturnWaitTime = 1000;
  82741. this._zoomStopsAnimation = false;
  82742. this._framingTime = 1500;
  82743. this._isPointerDown = false;
  82744. this._lastInteractionTime = -Infinity;
  82745. // Framing control
  82746. this._animatables = new Array();
  82747. this._betaIsAnimating = false;
  82748. }
  82749. Object.defineProperty(FramingBehavior.prototype, "name", {
  82750. get: function () {
  82751. return "Framing";
  82752. },
  82753. enumerable: true,
  82754. configurable: true
  82755. });
  82756. Object.defineProperty(FramingBehavior.prototype, "mode", {
  82757. /**
  82758. * Gets current mode used by the behavior.
  82759. */
  82760. get: function () {
  82761. return this._mode;
  82762. },
  82763. /**
  82764. * Sets the current mode used by the behavior
  82765. */
  82766. set: function (mode) {
  82767. this._mode = mode;
  82768. },
  82769. enumerable: true,
  82770. configurable: true
  82771. });
  82772. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  82773. /**
  82774. * Gets the scale applied to the radius
  82775. */
  82776. get: function () {
  82777. return this._radiusScale;
  82778. },
  82779. /**
  82780. * Sets the scale applied to the radius (1 by default)
  82781. */
  82782. set: function (radius) {
  82783. this._radiusScale = radius;
  82784. },
  82785. enumerable: true,
  82786. configurable: true
  82787. });
  82788. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  82789. /**
  82790. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82791. */
  82792. get: function () {
  82793. return this._positionScale;
  82794. },
  82795. /**
  82796. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82797. */
  82798. set: function (scale) {
  82799. this._positionScale = scale;
  82800. },
  82801. enumerable: true,
  82802. configurable: true
  82803. });
  82804. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  82805. /**
  82806. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82807. * behaviour is triggered, in radians.
  82808. */
  82809. get: function () {
  82810. return this._defaultElevation;
  82811. },
  82812. /**
  82813. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82814. * behaviour is triggered, in radians.
  82815. */
  82816. set: function (elevation) {
  82817. this._defaultElevation = elevation;
  82818. },
  82819. enumerable: true,
  82820. configurable: true
  82821. });
  82822. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  82823. /**
  82824. * Gets the time (in milliseconds) taken to return to the default beta position.
  82825. * Negative value indicates camera should not return to default.
  82826. */
  82827. get: function () {
  82828. return this._elevationReturnTime;
  82829. },
  82830. /**
  82831. * Sets the time (in milliseconds) taken to return to the default beta position.
  82832. * Negative value indicates camera should not return to default.
  82833. */
  82834. set: function (speed) {
  82835. this._elevationReturnTime = speed;
  82836. },
  82837. enumerable: true,
  82838. configurable: true
  82839. });
  82840. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  82841. /**
  82842. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82843. */
  82844. get: function () {
  82845. return this._elevationReturnWaitTime;
  82846. },
  82847. /**
  82848. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82849. */
  82850. set: function (time) {
  82851. this._elevationReturnWaitTime = time;
  82852. },
  82853. enumerable: true,
  82854. configurable: true
  82855. });
  82856. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  82857. /**
  82858. * Gets the flag that indicates if user zooming should stop animation.
  82859. */
  82860. get: function () {
  82861. return this._zoomStopsAnimation;
  82862. },
  82863. /**
  82864. * Sets the flag that indicates if user zooming should stop animation.
  82865. */
  82866. set: function (flag) {
  82867. this._zoomStopsAnimation = flag;
  82868. },
  82869. enumerable: true,
  82870. configurable: true
  82871. });
  82872. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  82873. /**
  82874. * Gets the transition time when framing the mesh, in milliseconds
  82875. */
  82876. get: function () {
  82877. return this._framingTime;
  82878. },
  82879. /**
  82880. * Sets the transition time when framing the mesh, in milliseconds
  82881. */
  82882. set: function (time) {
  82883. this._framingTime = time;
  82884. },
  82885. enumerable: true,
  82886. configurable: true
  82887. });
  82888. FramingBehavior.prototype.init = function () {
  82889. // Do notihng
  82890. };
  82891. FramingBehavior.prototype.attach = function (camera) {
  82892. var _this = this;
  82893. this._attachedCamera = camera;
  82894. var scene = this._attachedCamera.getScene();
  82895. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  82896. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  82897. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  82898. _this._isPointerDown = true;
  82899. return;
  82900. }
  82901. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  82902. _this._isPointerDown = false;
  82903. }
  82904. });
  82905. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  82906. if (mesh) {
  82907. _this.zoomOnMesh(mesh);
  82908. }
  82909. });
  82910. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82911. // Stop the animation if there is user interaction and the animation should stop for this interaction
  82912. _this._applyUserInteraction();
  82913. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  82914. // back to the default position after a given timeout
  82915. _this._maintainCameraAboveGround();
  82916. });
  82917. };
  82918. FramingBehavior.prototype.detach = function () {
  82919. if (!this._attachedCamera) {
  82920. return;
  82921. }
  82922. var scene = this._attachedCamera.getScene();
  82923. if (this._onPrePointerObservableObserver) {
  82924. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  82925. }
  82926. if (this._onAfterCheckInputsObserver) {
  82927. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82928. }
  82929. if (this._onMeshTargetChangedObserver) {
  82930. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82931. }
  82932. this._attachedCamera = null;
  82933. };
  82934. /**
  82935. * Targets the given mesh and updates zoom level accordingly.
  82936. * @param mesh The mesh to target.
  82937. * @param radius Optional. If a cached radius position already exists, overrides default.
  82938. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82939. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82940. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82941. */
  82942. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82943. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82944. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82945. mesh.computeWorldMatrix(true);
  82946. var boundingBox = mesh.getBoundingInfo().boundingBox;
  82947. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  82948. };
  82949. /**
  82950. * Targets the given mesh with its children and updates zoom level accordingly.
  82951. * @param mesh The mesh to target.
  82952. * @param radius Optional. If a cached radius position already exists, overrides default.
  82953. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82954. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82955. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82956. */
  82957. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82958. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82959. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82960. mesh.computeWorldMatrix(true);
  82961. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  82962. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  82963. };
  82964. /**
  82965. * Targets the given meshes with their children and updates zoom level accordingly.
  82966. * @param meshes The mesh to target.
  82967. * @param radius Optional. If a cached radius position already exists, overrides default.
  82968. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82969. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82970. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82971. */
  82972. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  82973. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82974. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82975. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  82976. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  82977. for (var i = 0; i < meshes.length; i++) {
  82978. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  82979. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  82980. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  82981. }
  82982. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  82983. };
  82984. /**
  82985. * Targets the given mesh and updates zoom level accordingly.
  82986. * @param mesh The mesh to target.
  82987. * @param radius Optional. If a cached radius position already exists, overrides default.
  82988. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82989. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82990. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82991. */
  82992. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  82993. var _this = this;
  82994. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82995. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82996. var zoomTarget;
  82997. if (!this._attachedCamera) {
  82998. return;
  82999. }
  83000. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  83001. var bottom = minimumWorld.y;
  83002. var top = maximumWorld.y;
  83003. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  83004. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  83005. if (focusOnOriginXZ) {
  83006. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  83007. }
  83008. else {
  83009. var centerWorld = minimumWorld.add(radiusWorld);
  83010. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  83011. }
  83012. if (!this._vectorTransition) {
  83013. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  83014. }
  83015. this._betaIsAnimating = true;
  83016. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  83017. if (animatable) {
  83018. this._animatables.push(animatable);
  83019. }
  83020. // sets the radius and lower radius bounds
  83021. // Small delta ensures camera is not always at lower zoom limit.
  83022. var radius = 0;
  83023. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  83024. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  83025. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  83026. radius = position;
  83027. }
  83028. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  83029. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  83030. if (this._attachedCamera.lowerRadiusLimit === null) {
  83031. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  83032. }
  83033. }
  83034. // Set sensibilities
  83035. var extend = maximumWorld.subtract(minimumWorld).length();
  83036. this._attachedCamera.panningSensibility = 5000 / extend;
  83037. this._attachedCamera.wheelPrecision = 100 / radius;
  83038. // transition to new radius
  83039. if (!this._radiusTransition) {
  83040. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  83041. }
  83042. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  83043. if (onAnimationEnd) {
  83044. onAnimationEnd();
  83045. }
  83046. if (_this._attachedCamera) {
  83047. _this._attachedCamera.storeState();
  83048. }
  83049. });
  83050. if (animatable) {
  83051. this._animatables.push(animatable);
  83052. }
  83053. };
  83054. /**
  83055. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  83056. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  83057. * frustum width.
  83058. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  83059. * to fully enclose the mesh in the viewing frustum.
  83060. */
  83061. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  83062. var size = maximumWorld.subtract(minimumWorld);
  83063. var boxVectorGlobalDiagonal = size.length();
  83064. var frustumSlope = this._getFrustumSlope();
  83065. // Formula for setting distance
  83066. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  83067. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  83068. // Horizon distance
  83069. var radius = radiusWithoutFraming * this._radiusScale;
  83070. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  83071. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  83072. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  83073. var camera = this._attachedCamera;
  83074. if (!camera) {
  83075. return 0;
  83076. }
  83077. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  83078. // Don't exceed the requested limit
  83079. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  83080. }
  83081. // Don't exceed the upper radius limit
  83082. if (camera.upperRadiusLimit) {
  83083. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  83084. }
  83085. return distance;
  83086. };
  83087. /**
  83088. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  83089. * is automatically returned to its default position (expected to be above ground plane).
  83090. */
  83091. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  83092. var _this = this;
  83093. if (this._elevationReturnTime < 0) {
  83094. return;
  83095. }
  83096. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  83097. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  83098. var limitBeta = Math.PI * 0.5;
  83099. // Bring the camera back up if below the ground plane
  83100. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  83101. this._betaIsAnimating = true;
  83102. //Transition to new position
  83103. this.stopAllAnimations();
  83104. if (!this._betaTransition) {
  83105. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  83106. }
  83107. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  83108. _this._clearAnimationLocks();
  83109. _this.stopAllAnimations();
  83110. });
  83111. if (animatabe) {
  83112. this._animatables.push(animatabe);
  83113. }
  83114. }
  83115. };
  83116. /**
  83117. * Returns the frustum slope based on the canvas ratio and camera FOV
  83118. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  83119. */
  83120. FramingBehavior.prototype._getFrustumSlope = function () {
  83121. // Calculate the viewport ratio
  83122. // Aspect Ratio is Height/Width.
  83123. var camera = this._attachedCamera;
  83124. if (!camera) {
  83125. return BABYLON.Vector2.Zero();
  83126. }
  83127. var engine = camera.getScene().getEngine();
  83128. var aspectRatio = engine.getAspectRatio(camera);
  83129. // Camera FOV is the vertical field of view (top-bottom) in radians.
  83130. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  83131. var frustumSlopeY = Math.tan(camera.fov / 2);
  83132. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  83133. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  83134. // along the forward vector.
  83135. var frustumSlopeX = frustumSlopeY * aspectRatio;
  83136. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  83137. };
  83138. /**
  83139. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  83140. */
  83141. FramingBehavior.prototype._clearAnimationLocks = function () {
  83142. this._betaIsAnimating = false;
  83143. };
  83144. /**
  83145. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  83146. */
  83147. FramingBehavior.prototype._applyUserInteraction = function () {
  83148. if (this.isUserIsMoving) {
  83149. this._lastInteractionTime = BABYLON.Tools.Now;
  83150. this.stopAllAnimations();
  83151. this._clearAnimationLocks();
  83152. }
  83153. };
  83154. /**
  83155. * Stops and removes all animations that have been applied to the camera
  83156. */
  83157. FramingBehavior.prototype.stopAllAnimations = function () {
  83158. if (this._attachedCamera) {
  83159. this._attachedCamera.animations = [];
  83160. }
  83161. while (this._animatables.length) {
  83162. if (this._animatables[0]) {
  83163. this._animatables[0].onAnimationEnd = null;
  83164. this._animatables[0].stop();
  83165. }
  83166. this._animatables.shift();
  83167. }
  83168. };
  83169. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  83170. /**
  83171. * Gets a value indicating if the user is moving the camera
  83172. */
  83173. get: function () {
  83174. if (!this._attachedCamera) {
  83175. return false;
  83176. }
  83177. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  83178. this._attachedCamera.inertialBetaOffset !== 0 ||
  83179. this._attachedCamera.inertialRadiusOffset !== 0 ||
  83180. this._attachedCamera.inertialPanningX !== 0 ||
  83181. this._attachedCamera.inertialPanningY !== 0 ||
  83182. this._isPointerDown;
  83183. },
  83184. enumerable: true,
  83185. configurable: true
  83186. });
  83187. /**
  83188. * The easing function used by animations
  83189. */
  83190. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  83191. /**
  83192. * The easing mode used by animations
  83193. */
  83194. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  83195. // Statics
  83196. /**
  83197. * The camera can move all the way towards the mesh.
  83198. */
  83199. FramingBehavior.IgnoreBoundsSizeMode = 0;
  83200. /**
  83201. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  83202. */
  83203. FramingBehavior.FitFrustumSidesMode = 1;
  83204. return FramingBehavior;
  83205. }());
  83206. BABYLON.FramingBehavior = FramingBehavior;
  83207. })(BABYLON || (BABYLON = {}));
  83208. //# sourceMappingURL=babylon.framingBehavior.js.map
  83209. var BABYLON;
  83210. (function (BABYLON) {
  83211. /**
  83212. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  83213. */
  83214. var BouncingBehavior = /** @class */ (function () {
  83215. function BouncingBehavior() {
  83216. /**
  83217. * The duration of the animation, in milliseconds
  83218. */
  83219. this.transitionDuration = 450;
  83220. /**
  83221. * Length of the distance animated by the transition when lower radius is reached
  83222. */
  83223. this.lowerRadiusTransitionRange = 2;
  83224. /**
  83225. * Length of the distance animated by the transition when upper radius is reached
  83226. */
  83227. this.upperRadiusTransitionRange = -2;
  83228. this._autoTransitionRange = false;
  83229. // Animations
  83230. this._radiusIsAnimating = false;
  83231. this._radiusBounceTransition = null;
  83232. this._animatables = new Array();
  83233. }
  83234. Object.defineProperty(BouncingBehavior.prototype, "name", {
  83235. get: function () {
  83236. return "Bouncing";
  83237. },
  83238. enumerable: true,
  83239. configurable: true
  83240. });
  83241. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  83242. /**
  83243. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  83244. */
  83245. get: function () {
  83246. return this._autoTransitionRange;
  83247. },
  83248. /**
  83249. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  83250. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  83251. */
  83252. set: function (value) {
  83253. var _this = this;
  83254. if (this._autoTransitionRange === value) {
  83255. return;
  83256. }
  83257. this._autoTransitionRange = value;
  83258. var camera = this._attachedCamera;
  83259. if (!camera) {
  83260. return;
  83261. }
  83262. if (value) {
  83263. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  83264. if (!mesh) {
  83265. return;
  83266. }
  83267. mesh.computeWorldMatrix(true);
  83268. var diagonal = mesh.getBoundingInfo().diagonalLength;
  83269. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  83270. _this.upperRadiusTransitionRange = diagonal * 0.05;
  83271. });
  83272. }
  83273. else if (this._onMeshTargetChangedObserver) {
  83274. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  83275. }
  83276. },
  83277. enumerable: true,
  83278. configurable: true
  83279. });
  83280. BouncingBehavior.prototype.init = function () {
  83281. // Do notihng
  83282. };
  83283. BouncingBehavior.prototype.attach = function (camera) {
  83284. var _this = this;
  83285. this._attachedCamera = camera;
  83286. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  83287. if (!_this._attachedCamera) {
  83288. return;
  83289. }
  83290. // Add the bounce animation to the lower radius limit
  83291. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  83292. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  83293. }
  83294. // Add the bounce animation to the upper radius limit
  83295. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  83296. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  83297. }
  83298. });
  83299. };
  83300. BouncingBehavior.prototype.detach = function () {
  83301. if (!this._attachedCamera) {
  83302. return;
  83303. }
  83304. if (this._onAfterCheckInputsObserver) {
  83305. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  83306. }
  83307. if (this._onMeshTargetChangedObserver) {
  83308. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  83309. }
  83310. this._attachedCamera = null;
  83311. };
  83312. /**
  83313. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  83314. * @param radiusLimit The limit to check against.
  83315. * @return Bool to indicate if at limit.
  83316. */
  83317. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  83318. if (!this._attachedCamera) {
  83319. return false;
  83320. }
  83321. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  83322. return true;
  83323. }
  83324. return false;
  83325. };
  83326. /**
  83327. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  83328. * @param radiusDelta The delta by which to animate to. Can be negative.
  83329. */
  83330. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  83331. var _this = this;
  83332. if (!this._attachedCamera) {
  83333. return;
  83334. }
  83335. if (!this._radiusBounceTransition) {
  83336. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  83337. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  83338. }
  83339. // Prevent zoom until bounce has completed
  83340. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  83341. this._attachedCamera.wheelPrecision = Infinity;
  83342. this._attachedCamera.inertialRadiusOffset = 0;
  83343. // Animate to the radius limit
  83344. this.stopAllAnimations();
  83345. this._radiusIsAnimating = true;
  83346. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  83347. if (animatable) {
  83348. this._animatables.push(animatable);
  83349. }
  83350. };
  83351. /**
  83352. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  83353. */
  83354. BouncingBehavior.prototype._clearAnimationLocks = function () {
  83355. this._radiusIsAnimating = false;
  83356. if (this._attachedCamera) {
  83357. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  83358. }
  83359. };
  83360. /**
  83361. * Stops and removes all animations that have been applied to the camera
  83362. */
  83363. BouncingBehavior.prototype.stopAllAnimations = function () {
  83364. if (this._attachedCamera) {
  83365. this._attachedCamera.animations = [];
  83366. }
  83367. while (this._animatables.length) {
  83368. this._animatables[0].onAnimationEnd = null;
  83369. this._animatables[0].stop();
  83370. this._animatables.shift();
  83371. }
  83372. };
  83373. /**
  83374. * The easing function used by animations
  83375. */
  83376. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  83377. /**
  83378. * The easing mode used by animations
  83379. */
  83380. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  83381. return BouncingBehavior;
  83382. }());
  83383. BABYLON.BouncingBehavior = BouncingBehavior;
  83384. })(BABYLON || (BABYLON = {}));
  83385. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  83386. var BABYLON;
  83387. (function (BABYLON) {
  83388. var AutoRotationBehavior = /** @class */ (function () {
  83389. function AutoRotationBehavior() {
  83390. this._zoomStopsAnimation = false;
  83391. this._idleRotationSpeed = 0.05;
  83392. this._idleRotationWaitTime = 2000;
  83393. this._idleRotationSpinupTime = 2000;
  83394. this._isPointerDown = false;
  83395. this._lastFrameTime = null;
  83396. this._lastInteractionTime = -Infinity;
  83397. this._cameraRotationSpeed = 0;
  83398. this._lastFrameRadius = 0;
  83399. }
  83400. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  83401. get: function () {
  83402. return "AutoRotation";
  83403. },
  83404. enumerable: true,
  83405. configurable: true
  83406. });
  83407. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  83408. /**
  83409. * Gets the flag that indicates if user zooming should stop animation.
  83410. */
  83411. get: function () {
  83412. return this._zoomStopsAnimation;
  83413. },
  83414. /**
  83415. * Sets the flag that indicates if user zooming should stop animation.
  83416. */
  83417. set: function (flag) {
  83418. this._zoomStopsAnimation = flag;
  83419. },
  83420. enumerable: true,
  83421. configurable: true
  83422. });
  83423. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  83424. /**
  83425. * Gets the default speed at which the camera rotates around the model.
  83426. */
  83427. get: function () {
  83428. return this._idleRotationSpeed;
  83429. },
  83430. /**
  83431. * Sets the default speed at which the camera rotates around the model.
  83432. */
  83433. set: function (speed) {
  83434. this._idleRotationSpeed = speed;
  83435. },
  83436. enumerable: true,
  83437. configurable: true
  83438. });
  83439. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  83440. /**
  83441. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  83442. */
  83443. get: function () {
  83444. return this._idleRotationWaitTime;
  83445. },
  83446. /**
  83447. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  83448. */
  83449. set: function (time) {
  83450. this._idleRotationWaitTime = time;
  83451. },
  83452. enumerable: true,
  83453. configurable: true
  83454. });
  83455. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  83456. /**
  83457. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  83458. */
  83459. get: function () {
  83460. return this._idleRotationSpinupTime;
  83461. },
  83462. /**
  83463. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  83464. */
  83465. set: function (time) {
  83466. this._idleRotationSpinupTime = time;
  83467. },
  83468. enumerable: true,
  83469. configurable: true
  83470. });
  83471. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  83472. /**
  83473. * Gets a value indicating if the camera is currently rotating because of this behavior
  83474. */
  83475. get: function () {
  83476. return Math.abs(this._cameraRotationSpeed) > 0;
  83477. },
  83478. enumerable: true,
  83479. configurable: true
  83480. });
  83481. AutoRotationBehavior.prototype.init = function () {
  83482. // Do notihng
  83483. };
  83484. AutoRotationBehavior.prototype.attach = function (camera) {
  83485. var _this = this;
  83486. this._attachedCamera = camera;
  83487. var scene = this._attachedCamera.getScene();
  83488. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  83489. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  83490. _this._isPointerDown = true;
  83491. return;
  83492. }
  83493. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  83494. _this._isPointerDown = false;
  83495. }
  83496. });
  83497. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  83498. var now = BABYLON.Tools.Now;
  83499. var dt = 0;
  83500. if (_this._lastFrameTime != null) {
  83501. dt = now - _this._lastFrameTime;
  83502. }
  83503. _this._lastFrameTime = now;
  83504. // Stop the animation if there is user interaction and the animation should stop for this interaction
  83505. _this._applyUserInteraction();
  83506. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  83507. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  83508. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  83509. // Step camera rotation by rotation speed
  83510. if (_this._attachedCamera) {
  83511. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  83512. }
  83513. });
  83514. };
  83515. AutoRotationBehavior.prototype.detach = function () {
  83516. if (!this._attachedCamera) {
  83517. return;
  83518. }
  83519. var scene = this._attachedCamera.getScene();
  83520. if (this._onPrePointerObservableObserver) {
  83521. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  83522. }
  83523. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  83524. this._attachedCamera = null;
  83525. };
  83526. /**
  83527. * Returns true if user is scrolling.
  83528. * @return true if user is scrolling.
  83529. */
  83530. AutoRotationBehavior.prototype._userIsZooming = function () {
  83531. if (!this._attachedCamera) {
  83532. return false;
  83533. }
  83534. return this._attachedCamera.inertialRadiusOffset !== 0;
  83535. };
  83536. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  83537. if (!this._attachedCamera) {
  83538. return false;
  83539. }
  83540. var zoomHasHitLimit = false;
  83541. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  83542. zoomHasHitLimit = true;
  83543. }
  83544. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  83545. this._lastFrameRadius = this._attachedCamera.radius;
  83546. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  83547. };
  83548. /**
  83549. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  83550. */
  83551. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  83552. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  83553. this._lastInteractionTime = BABYLON.Tools.Now;
  83554. }
  83555. };
  83556. // Tools
  83557. AutoRotationBehavior.prototype._userIsMoving = function () {
  83558. if (!this._attachedCamera) {
  83559. return false;
  83560. }
  83561. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  83562. this._attachedCamera.inertialBetaOffset !== 0 ||
  83563. this._attachedCamera.inertialRadiusOffset !== 0 ||
  83564. this._attachedCamera.inertialPanningX !== 0 ||
  83565. this._attachedCamera.inertialPanningY !== 0 ||
  83566. this._isPointerDown;
  83567. };
  83568. return AutoRotationBehavior;
  83569. }());
  83570. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  83571. })(BABYLON || (BABYLON = {}));
  83572. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  83573. var BABYLON;
  83574. (function (BABYLON) {
  83575. var NullEngineOptions = /** @class */ (function () {
  83576. function NullEngineOptions() {
  83577. this.renderWidth = 512;
  83578. this.renderHeight = 256;
  83579. this.textureSize = 512;
  83580. this.deterministicLockstep = false;
  83581. this.lockstepMaxSteps = 4;
  83582. }
  83583. return NullEngineOptions;
  83584. }());
  83585. BABYLON.NullEngineOptions = NullEngineOptions;
  83586. /**
  83587. * The null engine class provides support for headless version of babylon.js.
  83588. * This can be used in server side scenario or for testing purposes
  83589. */
  83590. var NullEngine = /** @class */ (function (_super) {
  83591. __extends(NullEngine, _super);
  83592. function NullEngine(options) {
  83593. if (options === void 0) { options = new NullEngineOptions(); }
  83594. var _this = _super.call(this, null) || this;
  83595. if (options.deterministicLockstep === undefined) {
  83596. options.deterministicLockstep = false;
  83597. }
  83598. if (options.lockstepMaxSteps === undefined) {
  83599. options.lockstepMaxSteps = 4;
  83600. }
  83601. _this._options = options;
  83602. // Init caps
  83603. // We consider we are on a webgl1 capable device
  83604. _this._caps = new BABYLON.EngineCapabilities();
  83605. _this._caps.maxTexturesImageUnits = 16;
  83606. _this._caps.maxVertexTextureImageUnits = 16;
  83607. _this._caps.maxTextureSize = 512;
  83608. _this._caps.maxCubemapTextureSize = 512;
  83609. _this._caps.maxRenderTextureSize = 512;
  83610. _this._caps.maxVertexAttribs = 16;
  83611. _this._caps.maxVaryingVectors = 16;
  83612. _this._caps.maxFragmentUniformVectors = 16;
  83613. _this._caps.maxVertexUniformVectors = 16;
  83614. // Extensions
  83615. _this._caps.standardDerivatives = false;
  83616. _this._caps.astc = null;
  83617. _this._caps.s3tc = null;
  83618. _this._caps.pvrtc = null;
  83619. _this._caps.etc1 = null;
  83620. _this._caps.etc2 = null;
  83621. _this._caps.textureAnisotropicFilterExtension = null;
  83622. _this._caps.maxAnisotropy = 0;
  83623. _this._caps.uintIndices = false;
  83624. _this._caps.fragmentDepthSupported = false;
  83625. _this._caps.highPrecisionShaderSupported = true;
  83626. _this._caps.colorBufferFloat = false;
  83627. _this._caps.textureFloat = false;
  83628. _this._caps.textureFloatLinearFiltering = false;
  83629. _this._caps.textureFloatRender = false;
  83630. _this._caps.textureHalfFloat = false;
  83631. _this._caps.textureHalfFloatLinearFiltering = false;
  83632. _this._caps.textureHalfFloatRender = false;
  83633. _this._caps.textureLOD = false;
  83634. _this._caps.drawBuffersExtension = false;
  83635. _this._caps.depthTextureExtension = false;
  83636. _this._caps.vertexArrayObject = false;
  83637. _this._caps.instancedArrays = false;
  83638. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  83639. // Wrappers
  83640. if (typeof URL === "undefined") {
  83641. URL = {
  83642. createObjectURL: function () { },
  83643. revokeObjectURL: function () { }
  83644. };
  83645. }
  83646. if (typeof Blob === "undefined") {
  83647. Blob = function () { };
  83648. }
  83649. return _this;
  83650. }
  83651. NullEngine.prototype.isDeterministicLockStep = function () {
  83652. return this._options.deterministicLockstep;
  83653. };
  83654. NullEngine.prototype.getLockstepMaxSteps = function () {
  83655. return this._options.lockstepMaxSteps;
  83656. };
  83657. NullEngine.prototype.createVertexBuffer = function (vertices) {
  83658. return {
  83659. capacity: 0,
  83660. references: 1,
  83661. is32Bits: false
  83662. };
  83663. };
  83664. NullEngine.prototype.createIndexBuffer = function (indices) {
  83665. return {
  83666. capacity: 0,
  83667. references: 1,
  83668. is32Bits: false
  83669. };
  83670. };
  83671. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  83672. if (stencil === void 0) { stencil = false; }
  83673. };
  83674. NullEngine.prototype.getRenderWidth = function (useScreen) {
  83675. if (useScreen === void 0) { useScreen = false; }
  83676. if (!useScreen && this._currentRenderTarget) {
  83677. return this._currentRenderTarget.width;
  83678. }
  83679. return this._options.renderWidth;
  83680. };
  83681. NullEngine.prototype.getRenderHeight = function (useScreen) {
  83682. if (useScreen === void 0) { useScreen = false; }
  83683. if (!useScreen && this._currentRenderTarget) {
  83684. return this._currentRenderTarget.height;
  83685. }
  83686. return this._options.renderHeight;
  83687. };
  83688. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  83689. this._cachedViewport = viewport;
  83690. };
  83691. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  83692. return {
  83693. transformFeedback: null,
  83694. __SPECTOR_rebuildProgram: null
  83695. };
  83696. };
  83697. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  83698. return [];
  83699. };
  83700. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  83701. return [];
  83702. };
  83703. NullEngine.prototype.bindSamplers = function (effect) {
  83704. this._currentEffect = null;
  83705. };
  83706. NullEngine.prototype.enableEffect = function (effect) {
  83707. this._currentEffect = effect;
  83708. if (effect.onBind) {
  83709. effect.onBind(effect);
  83710. }
  83711. effect.onBindObservable.notifyObservers(effect);
  83712. };
  83713. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  83714. if (zOffset === void 0) { zOffset = 0; }
  83715. if (reverseSide === void 0) { reverseSide = false; }
  83716. };
  83717. NullEngine.prototype.setIntArray = function (uniform, array) {
  83718. };
  83719. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  83720. };
  83721. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  83722. };
  83723. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  83724. };
  83725. NullEngine.prototype.setFloatArray = function (uniform, array) {
  83726. };
  83727. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  83728. };
  83729. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  83730. };
  83731. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  83732. };
  83733. NullEngine.prototype.setArray = function (uniform, array) {
  83734. };
  83735. NullEngine.prototype.setArray2 = function (uniform, array) {
  83736. };
  83737. NullEngine.prototype.setArray3 = function (uniform, array) {
  83738. };
  83739. NullEngine.prototype.setArray4 = function (uniform, array) {
  83740. };
  83741. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  83742. };
  83743. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  83744. };
  83745. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  83746. };
  83747. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  83748. };
  83749. NullEngine.prototype.setFloat = function (uniform, value) {
  83750. };
  83751. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  83752. };
  83753. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  83754. };
  83755. NullEngine.prototype.setBool = function (uniform, bool) {
  83756. };
  83757. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  83758. };
  83759. NullEngine.prototype.setColor3 = function (uniform, color3) {
  83760. };
  83761. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  83762. };
  83763. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  83764. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  83765. if (this._alphaMode === mode) {
  83766. return;
  83767. }
  83768. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  83769. if (!noDepthWriteChange) {
  83770. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  83771. }
  83772. this._alphaMode = mode;
  83773. };
  83774. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  83775. };
  83776. NullEngine.prototype.wipeCaches = function (bruteForce) {
  83777. if (this.preventCacheWipeBetweenFrames) {
  83778. return;
  83779. }
  83780. this.resetTextureCache();
  83781. this._currentEffect = null;
  83782. if (bruteForce) {
  83783. this._currentProgram = null;
  83784. this._stencilState.reset();
  83785. this._depthCullingState.reset();
  83786. this.setDepthFunctionToLessOrEqual();
  83787. this._alphaState.reset();
  83788. }
  83789. this._cachedVertexBuffers = null;
  83790. this._cachedIndexBuffer = null;
  83791. this._cachedEffectForVertexBuffers = null;
  83792. };
  83793. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  83794. };
  83795. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  83796. };
  83797. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  83798. };
  83799. NullEngine.prototype._createTexture = function () {
  83800. return {};
  83801. };
  83802. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  83803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  83804. if (onLoad === void 0) { onLoad = null; }
  83805. if (onError === void 0) { onError = null; }
  83806. if (buffer === void 0) { buffer = null; }
  83807. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  83808. var url = String(urlArg);
  83809. texture.url = url;
  83810. texture.generateMipMaps = !noMipmap;
  83811. texture.samplingMode = samplingMode;
  83812. texture.invertY = invertY;
  83813. texture.baseWidth = this._options.textureSize;
  83814. texture.baseHeight = this._options.textureSize;
  83815. texture.width = this._options.textureSize;
  83816. texture.height = this._options.textureSize;
  83817. if (format) {
  83818. texture.format = format;
  83819. }
  83820. texture.isReady = true;
  83821. if (onLoad) {
  83822. onLoad();
  83823. }
  83824. return texture;
  83825. };
  83826. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  83827. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  83828. if (options !== undefined && typeof options === "object") {
  83829. fullOptions.generateMipMaps = options.generateMipMaps;
  83830. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  83831. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  83832. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  83833. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  83834. }
  83835. else {
  83836. fullOptions.generateMipMaps = options;
  83837. fullOptions.generateDepthBuffer = true;
  83838. fullOptions.generateStencilBuffer = false;
  83839. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83840. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  83841. }
  83842. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  83843. var width = size.width || size;
  83844. var height = size.height || size;
  83845. texture._depthStencilBuffer = {};
  83846. texture._framebuffer = {};
  83847. texture.baseWidth = width;
  83848. texture.baseHeight = height;
  83849. texture.width = width;
  83850. texture.height = height;
  83851. texture.isReady = true;
  83852. texture.samples = 1;
  83853. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  83854. texture.samplingMode = fullOptions.samplingMode;
  83855. texture.type = fullOptions.type;
  83856. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  83857. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  83858. return texture;
  83859. };
  83860. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  83861. texture.samplingMode = samplingMode;
  83862. };
  83863. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  83864. if (this._currentRenderTarget) {
  83865. this.unBindFramebuffer(this._currentRenderTarget);
  83866. }
  83867. this._currentRenderTarget = texture;
  83868. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  83869. if (this._cachedViewport && !forceFullscreenViewport) {
  83870. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  83871. }
  83872. };
  83873. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  83874. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  83875. this._currentRenderTarget = null;
  83876. if (onBeforeUnbind) {
  83877. if (texture._MSAAFramebuffer) {
  83878. this._currentFramebuffer = texture._framebuffer;
  83879. }
  83880. onBeforeUnbind();
  83881. }
  83882. this._currentFramebuffer = null;
  83883. };
  83884. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  83885. var vbo = {
  83886. capacity: 1,
  83887. references: 1,
  83888. is32Bits: false
  83889. };
  83890. return vbo;
  83891. };
  83892. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  83893. if (offset === void 0) { offset = 0; }
  83894. };
  83895. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  83896. };
  83897. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  83898. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  83899. this._boundTexturesCache[this._activeChannel] = texture;
  83900. }
  83901. };
  83902. NullEngine.prototype._bindTexture = function (channel, texture) {
  83903. if (channel < 0) {
  83904. return;
  83905. }
  83906. this._bindTextureDirectly(0, texture);
  83907. };
  83908. NullEngine.prototype._releaseBuffer = function (buffer) {
  83909. buffer.references--;
  83910. if (buffer.references === 0) {
  83911. return true;
  83912. }
  83913. return false;
  83914. };
  83915. return NullEngine;
  83916. }(BABYLON.Engine));
  83917. BABYLON.NullEngine = NullEngine;
  83918. })(BABYLON || (BABYLON = {}));
  83919. //# sourceMappingURL=babylon.nullEngine.js.map
  83920. var BABYLON;
  83921. (function (BABYLON) {
  83922. /**
  83923. * This class can be used to get instrumentation data from a Babylon engine
  83924. */
  83925. var EngineInstrumentation = /** @class */ (function () {
  83926. function EngineInstrumentation(engine) {
  83927. this.engine = engine;
  83928. this._captureGPUFrameTime = false;
  83929. this._gpuFrameTime = new BABYLON.PerfCounter();
  83930. this._captureShaderCompilationTime = false;
  83931. this._shaderCompilationTime = new BABYLON.PerfCounter();
  83932. // Observers
  83933. this._onBeginFrameObserver = null;
  83934. this._onEndFrameObserver = null;
  83935. this._onBeforeShaderCompilationObserver = null;
  83936. this._onAfterShaderCompilationObserver = null;
  83937. }
  83938. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  83939. // Properties
  83940. /**
  83941. * Gets the perf counter used for GPU frame time
  83942. */
  83943. get: function () {
  83944. return this._gpuFrameTime;
  83945. },
  83946. enumerable: true,
  83947. configurable: true
  83948. });
  83949. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  83950. /**
  83951. * Gets the GPU frame time capture status
  83952. */
  83953. get: function () {
  83954. return this._captureGPUFrameTime;
  83955. },
  83956. /**
  83957. * Enable or disable the GPU frame time capture
  83958. */
  83959. set: function (value) {
  83960. var _this = this;
  83961. if (value === this._captureGPUFrameTime) {
  83962. return;
  83963. }
  83964. this._captureGPUFrameTime = value;
  83965. if (value) {
  83966. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  83967. if (!_this._gpuFrameTimeToken) {
  83968. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  83969. }
  83970. });
  83971. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  83972. if (!_this._gpuFrameTimeToken) {
  83973. return;
  83974. }
  83975. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  83976. if (time > -1) {
  83977. _this._gpuFrameTimeToken = null;
  83978. _this._gpuFrameTime.fetchNewFrame();
  83979. _this._gpuFrameTime.addCount(time, true);
  83980. }
  83981. });
  83982. }
  83983. else {
  83984. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  83985. this._onBeginFrameObserver = null;
  83986. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  83987. this._onEndFrameObserver = null;
  83988. }
  83989. },
  83990. enumerable: true,
  83991. configurable: true
  83992. });
  83993. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  83994. /**
  83995. * Gets the perf counter used for shader compilation time
  83996. */
  83997. get: function () {
  83998. return this._shaderCompilationTime;
  83999. },
  84000. enumerable: true,
  84001. configurable: true
  84002. });
  84003. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  84004. /**
  84005. * Gets the shader compilation time capture status
  84006. */
  84007. get: function () {
  84008. return this._captureShaderCompilationTime;
  84009. },
  84010. /**
  84011. * Enable or disable the shader compilation time capture
  84012. */
  84013. set: function (value) {
  84014. var _this = this;
  84015. if (value === this._captureShaderCompilationTime) {
  84016. return;
  84017. }
  84018. this._captureShaderCompilationTime = value;
  84019. if (value) {
  84020. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  84021. _this._shaderCompilationTime.fetchNewFrame();
  84022. _this._shaderCompilationTime.beginMonitoring();
  84023. });
  84024. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  84025. _this._shaderCompilationTime.endMonitoring();
  84026. });
  84027. }
  84028. else {
  84029. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  84030. this._onBeforeShaderCompilationObserver = null;
  84031. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  84032. this._onAfterShaderCompilationObserver = null;
  84033. }
  84034. },
  84035. enumerable: true,
  84036. configurable: true
  84037. });
  84038. EngineInstrumentation.prototype.dispose = function () {
  84039. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  84040. this._onBeginFrameObserver = null;
  84041. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  84042. this._onEndFrameObserver = null;
  84043. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  84044. this._onBeforeShaderCompilationObserver = null;
  84045. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  84046. this._onAfterShaderCompilationObserver = null;
  84047. this.engine = null;
  84048. };
  84049. return EngineInstrumentation;
  84050. }());
  84051. BABYLON.EngineInstrumentation = EngineInstrumentation;
  84052. })(BABYLON || (BABYLON = {}));
  84053. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  84054. var BABYLON;
  84055. (function (BABYLON) {
  84056. /**
  84057. * This class can be used to get instrumentation data from a Babylon engine
  84058. */
  84059. var SceneInstrumentation = /** @class */ (function () {
  84060. function SceneInstrumentation(scene) {
  84061. var _this = this;
  84062. this.scene = scene;
  84063. this._captureActiveMeshesEvaluationTime = false;
  84064. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  84065. this._captureRenderTargetsRenderTime = false;
  84066. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  84067. this._captureFrameTime = false;
  84068. this._frameTime = new BABYLON.PerfCounter();
  84069. this._captureRenderTime = false;
  84070. this._renderTime = new BABYLON.PerfCounter();
  84071. this._captureInterFrameTime = false;
  84072. this._interFrameTime = new BABYLON.PerfCounter();
  84073. this._captureParticlesRenderTime = false;
  84074. this._particlesRenderTime = new BABYLON.PerfCounter();
  84075. this._captureSpritesRenderTime = false;
  84076. this._spritesRenderTime = new BABYLON.PerfCounter();
  84077. this._capturePhysicsTime = false;
  84078. this._physicsTime = new BABYLON.PerfCounter();
  84079. this._captureAnimationsTime = false;
  84080. this._animationsTime = new BABYLON.PerfCounter();
  84081. // Observers
  84082. this._onBeforeActiveMeshesEvaluationObserver = null;
  84083. this._onAfterActiveMeshesEvaluationObserver = null;
  84084. this._onBeforeRenderTargetsRenderObserver = null;
  84085. this._onAfterRenderTargetsRenderObserver = null;
  84086. this._onAfterRenderObserver = null;
  84087. this._onBeforeDrawPhaseObserver = null;
  84088. this._onAfterDrawPhaseObserver = null;
  84089. this._onBeforeAnimationsObserver = null;
  84090. this._onBeforeParticlesRenderingObserver = null;
  84091. this._onAfterParticlesRenderingObserver = null;
  84092. this._onBeforeSpritesRenderingObserver = null;
  84093. this._onAfterSpritesRenderingObserver = null;
  84094. this._onBeforePhysicsObserver = null;
  84095. this._onAfterPhysicsObserver = null;
  84096. this._onAfterAnimationsObserver = null;
  84097. // Before render
  84098. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  84099. if (_this._captureActiveMeshesEvaluationTime) {
  84100. _this._activeMeshesEvaluationTime.fetchNewFrame();
  84101. }
  84102. if (_this._captureRenderTargetsRenderTime) {
  84103. _this._renderTargetsRenderTime.fetchNewFrame();
  84104. }
  84105. if (_this._captureFrameTime) {
  84106. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  84107. _this._frameTime.beginMonitoring();
  84108. }
  84109. if (_this._captureInterFrameTime) {
  84110. _this._interFrameTime.endMonitoring();
  84111. }
  84112. if (_this._captureParticlesRenderTime) {
  84113. _this._particlesRenderTime.fetchNewFrame();
  84114. }
  84115. if (_this._captureSpritesRenderTime) {
  84116. _this._spritesRenderTime.fetchNewFrame();
  84117. }
  84118. if (_this._captureAnimationsTime) {
  84119. _this._animationsTime.beginMonitoring();
  84120. }
  84121. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  84122. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  84123. });
  84124. // After render
  84125. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  84126. if (_this._captureFrameTime) {
  84127. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  84128. _this._frameTime.endMonitoring();
  84129. }
  84130. if (_this._captureRenderTime) {
  84131. _this._renderTime.endMonitoring(false);
  84132. }
  84133. if (_this._captureInterFrameTime) {
  84134. _this._interFrameTime.beginMonitoring();
  84135. }
  84136. });
  84137. }
  84138. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  84139. // Properties
  84140. /**
  84141. * Gets the perf counter used for active meshes evaluation time
  84142. */
  84143. get: function () {
  84144. return this._activeMeshesEvaluationTime;
  84145. },
  84146. enumerable: true,
  84147. configurable: true
  84148. });
  84149. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  84150. /**
  84151. * Gets the active meshes evaluation time capture status
  84152. */
  84153. get: function () {
  84154. return this._captureActiveMeshesEvaluationTime;
  84155. },
  84156. /**
  84157. * Enable or disable the active meshes evaluation time capture
  84158. */
  84159. set: function (value) {
  84160. var _this = this;
  84161. if (value === this._captureActiveMeshesEvaluationTime) {
  84162. return;
  84163. }
  84164. this._captureActiveMeshesEvaluationTime = value;
  84165. if (value) {
  84166. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  84167. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  84168. _this._activeMeshesEvaluationTime.beginMonitoring();
  84169. });
  84170. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  84171. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  84172. _this._activeMeshesEvaluationTime.endMonitoring();
  84173. });
  84174. }
  84175. else {
  84176. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  84177. this._onBeforeActiveMeshesEvaluationObserver = null;
  84178. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  84179. this._onAfterActiveMeshesEvaluationObserver = null;
  84180. }
  84181. },
  84182. enumerable: true,
  84183. configurable: true
  84184. });
  84185. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  84186. /**
  84187. * Gets the perf counter used for render targets render time
  84188. */
  84189. get: function () {
  84190. return this._renderTargetsRenderTime;
  84191. },
  84192. enumerable: true,
  84193. configurable: true
  84194. });
  84195. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  84196. /**
  84197. * Gets the render targets render time capture status
  84198. */
  84199. get: function () {
  84200. return this._captureRenderTargetsRenderTime;
  84201. },
  84202. /**
  84203. * Enable or disable the render targets render time capture
  84204. */
  84205. set: function (value) {
  84206. var _this = this;
  84207. if (value === this._captureRenderTargetsRenderTime) {
  84208. return;
  84209. }
  84210. this._captureRenderTargetsRenderTime = value;
  84211. if (value) {
  84212. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  84213. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  84214. _this._renderTargetsRenderTime.beginMonitoring();
  84215. });
  84216. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  84217. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  84218. _this._renderTargetsRenderTime.endMonitoring(false);
  84219. });
  84220. }
  84221. else {
  84222. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  84223. this._onBeforeRenderTargetsRenderObserver = null;
  84224. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  84225. this._onAfterRenderTargetsRenderObserver = null;
  84226. }
  84227. },
  84228. enumerable: true,
  84229. configurable: true
  84230. });
  84231. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  84232. /**
  84233. * Gets the perf counter used for particles render time
  84234. */
  84235. get: function () {
  84236. return this._particlesRenderTime;
  84237. },
  84238. enumerable: true,
  84239. configurable: true
  84240. });
  84241. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  84242. /**
  84243. * Gets the particles render time capture status
  84244. */
  84245. get: function () {
  84246. return this._captureParticlesRenderTime;
  84247. },
  84248. /**
  84249. * Enable or disable the particles render time capture
  84250. */
  84251. set: function (value) {
  84252. var _this = this;
  84253. if (value === this._captureParticlesRenderTime) {
  84254. return;
  84255. }
  84256. this._captureParticlesRenderTime = value;
  84257. if (value) {
  84258. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  84259. BABYLON.Tools.StartPerformanceCounter("Particles");
  84260. _this._particlesRenderTime.beginMonitoring();
  84261. });
  84262. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  84263. BABYLON.Tools.EndPerformanceCounter("Particles");
  84264. _this._particlesRenderTime.endMonitoring(false);
  84265. });
  84266. }
  84267. else {
  84268. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  84269. this._onBeforeParticlesRenderingObserver = null;
  84270. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  84271. this._onAfterParticlesRenderingObserver = null;
  84272. }
  84273. },
  84274. enumerable: true,
  84275. configurable: true
  84276. });
  84277. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  84278. /**
  84279. * Gets the perf counter used for sprites render time
  84280. */
  84281. get: function () {
  84282. return this._spritesRenderTime;
  84283. },
  84284. enumerable: true,
  84285. configurable: true
  84286. });
  84287. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  84288. /**
  84289. * Gets the sprites render time capture status
  84290. */
  84291. get: function () {
  84292. return this._captureSpritesRenderTime;
  84293. },
  84294. /**
  84295. * Enable or disable the sprites render time capture
  84296. */
  84297. set: function (value) {
  84298. var _this = this;
  84299. if (value === this._captureSpritesRenderTime) {
  84300. return;
  84301. }
  84302. this._captureSpritesRenderTime = value;
  84303. if (value) {
  84304. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  84305. BABYLON.Tools.StartPerformanceCounter("Sprites");
  84306. _this._spritesRenderTime.beginMonitoring();
  84307. });
  84308. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  84309. BABYLON.Tools.EndPerformanceCounter("Sprites");
  84310. _this._spritesRenderTime.endMonitoring(false);
  84311. });
  84312. }
  84313. else {
  84314. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  84315. this._onBeforeSpritesRenderingObserver = null;
  84316. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  84317. this._onAfterSpritesRenderingObserver = null;
  84318. }
  84319. },
  84320. enumerable: true,
  84321. configurable: true
  84322. });
  84323. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  84324. /**
  84325. * Gets the perf counter used for physics time
  84326. */
  84327. get: function () {
  84328. return this._physicsTime;
  84329. },
  84330. enumerable: true,
  84331. configurable: true
  84332. });
  84333. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  84334. /**
  84335. * Gets the physics time capture status
  84336. */
  84337. get: function () {
  84338. return this._capturePhysicsTime;
  84339. },
  84340. /**
  84341. * Enable or disable the physics time capture
  84342. */
  84343. set: function (value) {
  84344. var _this = this;
  84345. if (value === this._capturePhysicsTime) {
  84346. return;
  84347. }
  84348. this._capturePhysicsTime = value;
  84349. if (value) {
  84350. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  84351. BABYLON.Tools.StartPerformanceCounter("Physics");
  84352. _this._physicsTime.beginMonitoring();
  84353. });
  84354. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  84355. BABYLON.Tools.EndPerformanceCounter("Physics");
  84356. _this._physicsTime.endMonitoring();
  84357. });
  84358. }
  84359. else {
  84360. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  84361. this._onBeforePhysicsObserver = null;
  84362. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  84363. this._onAfterPhysicsObserver = null;
  84364. }
  84365. },
  84366. enumerable: true,
  84367. configurable: true
  84368. });
  84369. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  84370. /**
  84371. * Gets the perf counter used for animations time
  84372. */
  84373. get: function () {
  84374. return this._animationsTime;
  84375. },
  84376. enumerable: true,
  84377. configurable: true
  84378. });
  84379. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  84380. /**
  84381. * Gets the animations time capture status
  84382. */
  84383. get: function () {
  84384. return this._captureAnimationsTime;
  84385. },
  84386. /**
  84387. * Enable or disable the animations time capture
  84388. */
  84389. set: function (value) {
  84390. var _this = this;
  84391. if (value === this._captureAnimationsTime) {
  84392. return;
  84393. }
  84394. this._captureAnimationsTime = value;
  84395. if (value) {
  84396. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  84397. _this._animationsTime.endMonitoring();
  84398. });
  84399. }
  84400. else {
  84401. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  84402. this._onAfterAnimationsObserver = null;
  84403. }
  84404. },
  84405. enumerable: true,
  84406. configurable: true
  84407. });
  84408. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  84409. /**
  84410. * Gets the perf counter used for frame time capture
  84411. */
  84412. get: function () {
  84413. return this._frameTime;
  84414. },
  84415. enumerable: true,
  84416. configurable: true
  84417. });
  84418. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  84419. /**
  84420. * Gets the frame time capture status
  84421. */
  84422. get: function () {
  84423. return this._captureFrameTime;
  84424. },
  84425. /**
  84426. * Enable or disable the frame time capture
  84427. */
  84428. set: function (value) {
  84429. this._captureFrameTime = value;
  84430. },
  84431. enumerable: true,
  84432. configurable: true
  84433. });
  84434. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  84435. /**
  84436. * Gets the perf counter used for inter-frames time capture
  84437. */
  84438. get: function () {
  84439. return this._interFrameTime;
  84440. },
  84441. enumerable: true,
  84442. configurable: true
  84443. });
  84444. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  84445. /**
  84446. * Gets the inter-frames time capture status
  84447. */
  84448. get: function () {
  84449. return this._captureInterFrameTime;
  84450. },
  84451. /**
  84452. * Enable or disable the inter-frames time capture
  84453. */
  84454. set: function (value) {
  84455. this._captureInterFrameTime = value;
  84456. },
  84457. enumerable: true,
  84458. configurable: true
  84459. });
  84460. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  84461. /**
  84462. * Gets the perf counter used for render time capture
  84463. */
  84464. get: function () {
  84465. return this._renderTime;
  84466. },
  84467. enumerable: true,
  84468. configurable: true
  84469. });
  84470. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  84471. /**
  84472. * Gets the render time capture status
  84473. */
  84474. get: function () {
  84475. return this._captureRenderTime;
  84476. },
  84477. /**
  84478. * Enable or disable the render time capture
  84479. */
  84480. set: function (value) {
  84481. var _this = this;
  84482. if (value === this._captureRenderTime) {
  84483. return;
  84484. }
  84485. this._captureRenderTime = value;
  84486. if (value) {
  84487. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  84488. _this._renderTime.beginMonitoring();
  84489. BABYLON.Tools.StartPerformanceCounter("Main render");
  84490. });
  84491. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  84492. _this._renderTime.endMonitoring(false);
  84493. BABYLON.Tools.EndPerformanceCounter("Main render");
  84494. });
  84495. }
  84496. else {
  84497. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  84498. this._onBeforeDrawPhaseObserver = null;
  84499. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  84500. this._onAfterDrawPhaseObserver = null;
  84501. }
  84502. },
  84503. enumerable: true,
  84504. configurable: true
  84505. });
  84506. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  84507. /**
  84508. * Gets the perf counter used for draw calls
  84509. */
  84510. get: function () {
  84511. return this.scene.getEngine()._drawCalls;
  84512. },
  84513. enumerable: true,
  84514. configurable: true
  84515. });
  84516. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  84517. /**
  84518. * Gets the perf counter used for texture collisions
  84519. */
  84520. get: function () {
  84521. return this.scene.getEngine()._textureCollisions;
  84522. },
  84523. enumerable: true,
  84524. configurable: true
  84525. });
  84526. SceneInstrumentation.prototype.dispose = function () {
  84527. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  84528. this._onAfterRenderObserver = null;
  84529. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  84530. this._onBeforeActiveMeshesEvaluationObserver = null;
  84531. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  84532. this._onAfterActiveMeshesEvaluationObserver = null;
  84533. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  84534. this._onBeforeRenderTargetsRenderObserver = null;
  84535. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  84536. this._onAfterRenderTargetsRenderObserver = null;
  84537. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  84538. this._onBeforeAnimationsObserver = null;
  84539. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  84540. this._onBeforeParticlesRenderingObserver = null;
  84541. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  84542. this._onAfterParticlesRenderingObserver = null;
  84543. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  84544. this._onBeforeSpritesRenderingObserver = null;
  84545. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  84546. this._onAfterSpritesRenderingObserver = null;
  84547. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  84548. this._onBeforeDrawPhaseObserver = null;
  84549. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  84550. this._onAfterDrawPhaseObserver = null;
  84551. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  84552. this._onBeforePhysicsObserver = null;
  84553. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  84554. this._onAfterPhysicsObserver = null;
  84555. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  84556. this._onAfterAnimationsObserver = null;
  84557. this.scene = null;
  84558. };
  84559. return SceneInstrumentation;
  84560. }());
  84561. BABYLON.SceneInstrumentation = SceneInstrumentation;
  84562. })(BABYLON || (BABYLON = {}));
  84563. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  84564. var BABYLON;
  84565. (function (BABYLON) {
  84566. var _TimeToken = /** @class */ (function () {
  84567. function _TimeToken() {
  84568. this._timeElapsedQueryEnded = false;
  84569. }
  84570. return _TimeToken;
  84571. }());
  84572. BABYLON._TimeToken = _TimeToken;
  84573. })(BABYLON || (BABYLON = {}));
  84574. //# sourceMappingURL=babylon.timeToken.js.map
  84575. var BABYLON;
  84576. (function (BABYLON) {
  84577. /**
  84578. * Background material defines definition.
  84579. * @ignore Mainly internal Use
  84580. */
  84581. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  84582. __extends(BackgroundMaterialDefines, _super);
  84583. /**
  84584. * Constructor of the defines.
  84585. */
  84586. function BackgroundMaterialDefines() {
  84587. var _this = _super.call(this) || this;
  84588. /**
  84589. * True if the diffuse texture is in use.
  84590. */
  84591. _this.DIFFUSE = false;
  84592. /**
  84593. * The direct UV channel to use.
  84594. */
  84595. _this.DIFFUSEDIRECTUV = 0;
  84596. /**
  84597. * True if the diffuse texture is in gamma space.
  84598. */
  84599. _this.GAMMADIFFUSE = false;
  84600. /**
  84601. * True if the diffuse texture has opacity in the alpha channel.
  84602. */
  84603. _this.DIFFUSEHASALPHA = false;
  84604. /**
  84605. * True if you want the material to fade to transparent at grazing angle.
  84606. */
  84607. _this.OPACITYFRESNEL = false;
  84608. /**
  84609. * True if an extra blur needs to be added in the reflection.
  84610. */
  84611. _this.REFLECTIONBLUR = false;
  84612. /**
  84613. * True if you want the material to fade to reflection at grazing angle.
  84614. */
  84615. _this.REFLECTIONFRESNEL = false;
  84616. /**
  84617. * True if you want the material to falloff as far as you move away from the scene center.
  84618. */
  84619. _this.REFLECTIONFALLOFF = false;
  84620. /**
  84621. * False if the current Webgl implementation does not support the texture lod extension.
  84622. */
  84623. _this.TEXTURELODSUPPORT = false;
  84624. /**
  84625. * True to ensure the data are premultiplied.
  84626. */
  84627. _this.PREMULTIPLYALPHA = false;
  84628. /**
  84629. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  84630. */
  84631. _this.USERGBCOLOR = false;
  84632. /**
  84633. * True to add noise in order to reduce the banding effect.
  84634. */
  84635. _this.NOISE = false;
  84636. // Image Processing Configuration.
  84637. _this.IMAGEPROCESSING = false;
  84638. _this.VIGNETTE = false;
  84639. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  84640. _this.VIGNETTEBLENDMODEOPAQUE = false;
  84641. _this.TONEMAPPING = false;
  84642. _this.CONTRAST = false;
  84643. _this.COLORCURVES = false;
  84644. _this.COLORGRADING = false;
  84645. _this.COLORGRADING3D = false;
  84646. _this.SAMPLER3DGREENDEPTH = false;
  84647. _this.SAMPLER3DBGRMAP = false;
  84648. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  84649. _this.EXPOSURE = false;
  84650. // Reflection.
  84651. _this.REFLECTION = false;
  84652. _this.REFLECTIONMAP_3D = false;
  84653. _this.REFLECTIONMAP_SPHERICAL = false;
  84654. _this.REFLECTIONMAP_PLANAR = false;
  84655. _this.REFLECTIONMAP_CUBIC = false;
  84656. _this.REFLECTIONMAP_PROJECTION = false;
  84657. _this.REFLECTIONMAP_SKYBOX = false;
  84658. _this.REFLECTIONMAP_EXPLICIT = false;
  84659. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  84660. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  84661. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  84662. _this.INVERTCUBICMAP = false;
  84663. _this.REFLECTIONMAP_OPPOSITEZ = false;
  84664. _this.LODINREFLECTIONALPHA = false;
  84665. _this.GAMMAREFLECTION = false;
  84666. // Default BJS.
  84667. _this.MAINUV1 = false;
  84668. _this.MAINUV2 = false;
  84669. _this.UV1 = false;
  84670. _this.UV2 = false;
  84671. _this.CLIPPLANE = false;
  84672. _this.POINTSIZE = false;
  84673. _this.FOG = false;
  84674. _this.NORMAL = false;
  84675. _this.NUM_BONE_INFLUENCERS = 0;
  84676. _this.BonesPerMesh = 0;
  84677. _this.INSTANCES = false;
  84678. _this.SHADOWFLOAT = false;
  84679. _this.rebuild();
  84680. return _this;
  84681. }
  84682. return BackgroundMaterialDefines;
  84683. }(BABYLON.MaterialDefines));
  84684. /**
  84685. * Background material used to create an efficient environement around your scene.
  84686. */
  84687. var BackgroundMaterial = /** @class */ (function (_super) {
  84688. __extends(BackgroundMaterial, _super);
  84689. /**
  84690. * Instantiates a Background Material in the given scene
  84691. * @param name The friendly name of the material
  84692. * @param scene The scene to add the material to
  84693. */
  84694. function BackgroundMaterial(name, scene) {
  84695. var _this = _super.call(this, name, scene) || this;
  84696. /**
  84697. * Key light Color (multiply against the R channel of the environement texture)
  84698. */
  84699. _this.primaryColor = BABYLON.Color3.White();
  84700. /**
  84701. * Key light Level (allowing HDR output of the background)
  84702. */
  84703. _this.primaryLevel = 1;
  84704. /**
  84705. * Secondary light Color (multiply against the G channel of the environement texture)
  84706. */
  84707. _this.secondaryColor = BABYLON.Color3.Gray();
  84708. /**
  84709. * Secondary light Level (allowing HDR output of the background)
  84710. */
  84711. _this.secondaryLevel = 1;
  84712. /**
  84713. * Tertiary light Color (multiply against the B channel of the environement texture)
  84714. */
  84715. _this.tertiaryColor = BABYLON.Color3.Black();
  84716. /**
  84717. * Tertiary light Level (allowing HDR output of the background)
  84718. */
  84719. _this.tertiaryLevel = 1;
  84720. /**
  84721. * Reflection Texture used in the material.
  84722. * Should be author in a specific way for the best result (refer to the documentation).
  84723. */
  84724. _this.reflectionTexture = null;
  84725. /**
  84726. * Reflection Texture level of blur.
  84727. *
  84728. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  84729. * texture twice.
  84730. */
  84731. _this.reflectionBlur = 0;
  84732. /**
  84733. * Diffuse Texture used in the material.
  84734. * Should be author in a specific way for the best result (refer to the documentation).
  84735. */
  84736. _this.diffuseTexture = null;
  84737. _this._shadowLights = null;
  84738. /**
  84739. * Specify the list of lights casting shadow on the material.
  84740. * All scene shadow lights will be included if null.
  84741. */
  84742. _this.shadowLights = null;
  84743. /**
  84744. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  84745. * soft lighting on the background.
  84746. */
  84747. _this.shadowBlurScale = 1;
  84748. /**
  84749. * Helps adjusting the shadow to a softer level if required.
  84750. * 0 means black shadows and 1 means no shadows.
  84751. */
  84752. _this.shadowLevel = 0;
  84753. /**
  84754. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  84755. * It is usually zero but might be interesting to modify according to your setup.
  84756. */
  84757. _this.sceneCenter = BABYLON.Vector3.Zero();
  84758. /**
  84759. * This helps specifying that the material is falling off to the sky box at grazing angle.
  84760. * This helps ensuring a nice transition when the camera goes under the ground.
  84761. */
  84762. _this.opacityFresnel = true;
  84763. /**
  84764. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  84765. * This helps adding a mirror texture on the ground.
  84766. */
  84767. _this.reflectionFresnel = false;
  84768. /**
  84769. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  84770. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  84771. */
  84772. _this.reflectionFalloffDistance = 0.0;
  84773. /**
  84774. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  84775. */
  84776. _this.reflectionAmount = 1.0;
  84777. /**
  84778. * This specifies the weight of the reflection at grazing angle.
  84779. */
  84780. _this.reflectionReflectance0 = 0.05;
  84781. /**
  84782. * This specifies the weight of the reflection at a perpendicular point of view.
  84783. */
  84784. _this.reflectionReflectance90 = 0.5;
  84785. /**
  84786. * Helps to directly use the maps channels instead of their level.
  84787. */
  84788. _this.useRGBColor = true;
  84789. /**
  84790. * This helps reducing the banding effect that could occur on the background.
  84791. */
  84792. _this.enableNoise = false;
  84793. _this._maxSimultaneousLights = 4;
  84794. /**
  84795. * Number of Simultaneous lights allowed on the material.
  84796. */
  84797. _this.maxSimultaneousLights = 4;
  84798. /**
  84799. * Keep track of the image processing observer to allow dispose and replace.
  84800. */
  84801. _this._imageProcessingObserver = null;
  84802. // Temp values kept as cache in the material.
  84803. _this._renderTargets = new BABYLON.SmartArray(16);
  84804. _this._reflectionControls = BABYLON.Vector4.Zero();
  84805. // Setup the default processing configuration to the scene.
  84806. _this._attachImageProcessingConfiguration(null);
  84807. _this.getRenderTargetTextures = function () {
  84808. _this._renderTargets.reset();
  84809. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  84810. _this._renderTargets.push(_this._diffuseTexture);
  84811. }
  84812. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  84813. _this._renderTargets.push(_this._reflectionTexture);
  84814. }
  84815. return _this._renderTargets;
  84816. };
  84817. return _this;
  84818. }
  84819. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  84820. /**
  84821. * Sets the reflection reflectance fresnel values according to the default standard
  84822. * empirically know to work well :-)
  84823. */
  84824. set: function (value) {
  84825. var reflectionWeight = value;
  84826. if (reflectionWeight < 0.5) {
  84827. reflectionWeight = reflectionWeight * 2.0;
  84828. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  84829. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  84830. }
  84831. else {
  84832. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  84833. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  84834. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  84835. }
  84836. },
  84837. enumerable: true,
  84838. configurable: true
  84839. });
  84840. /**
  84841. * Attaches a new image processing configuration to the PBR Material.
  84842. * @param configuration (if null the scene configuration will be use)
  84843. */
  84844. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  84845. var _this = this;
  84846. if (configuration === this._imageProcessingConfiguration) {
  84847. return;
  84848. }
  84849. // Detaches observer.
  84850. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84851. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84852. }
  84853. // Pick the scene configuration if needed.
  84854. if (!configuration) {
  84855. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  84856. }
  84857. else {
  84858. this._imageProcessingConfiguration = configuration;
  84859. }
  84860. // Attaches observer.
  84861. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  84862. _this._markAllSubMeshesAsImageProcessingDirty();
  84863. });
  84864. };
  84865. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  84866. /**
  84867. * Gets the image processing configuration used either in this material.
  84868. */
  84869. get: function () {
  84870. return this._imageProcessingConfiguration;
  84871. },
  84872. /**
  84873. * Sets the Default image processing configuration used either in the this material.
  84874. *
  84875. * If sets to null, the scene one is in use.
  84876. */
  84877. set: function (value) {
  84878. this._attachImageProcessingConfiguration(value);
  84879. // Ensure the effect will be rebuilt.
  84880. this._markAllSubMeshesAsTexturesDirty();
  84881. },
  84882. enumerable: true,
  84883. configurable: true
  84884. });
  84885. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  84886. /**
  84887. * Gets wether the color curves effect is enabled.
  84888. */
  84889. get: function () {
  84890. return this.imageProcessingConfiguration.colorCurvesEnabled;
  84891. },
  84892. /**
  84893. * Sets wether the color curves effect is enabled.
  84894. */
  84895. set: function (value) {
  84896. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  84897. },
  84898. enumerable: true,
  84899. configurable: true
  84900. });
  84901. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  84902. /**
  84903. * Gets wether the color grading effect is enabled.
  84904. */
  84905. get: function () {
  84906. return this.imageProcessingConfiguration.colorGradingEnabled;
  84907. },
  84908. /**
  84909. * Gets wether the color grading effect is enabled.
  84910. */
  84911. set: function (value) {
  84912. this.imageProcessingConfiguration.colorGradingEnabled = value;
  84913. },
  84914. enumerable: true,
  84915. configurable: true
  84916. });
  84917. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  84918. /**
  84919. * Gets wether tonemapping is enabled or not.
  84920. */
  84921. get: function () {
  84922. return this._imageProcessingConfiguration.toneMappingEnabled;
  84923. },
  84924. /**
  84925. * Sets wether tonemapping is enabled or not
  84926. */
  84927. set: function (value) {
  84928. this._imageProcessingConfiguration.toneMappingEnabled = value;
  84929. },
  84930. enumerable: true,
  84931. configurable: true
  84932. });
  84933. ;
  84934. ;
  84935. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  84936. /**
  84937. * The camera exposure used on this material.
  84938. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  84939. * This corresponds to a photographic exposure.
  84940. */
  84941. get: function () {
  84942. return this._imageProcessingConfiguration.exposure;
  84943. },
  84944. /**
  84945. * The camera exposure used on this material.
  84946. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  84947. * This corresponds to a photographic exposure.
  84948. */
  84949. set: function (value) {
  84950. this._imageProcessingConfiguration.exposure = value;
  84951. },
  84952. enumerable: true,
  84953. configurable: true
  84954. });
  84955. ;
  84956. ;
  84957. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  84958. /**
  84959. * Gets The camera contrast used on this material.
  84960. */
  84961. get: function () {
  84962. return this._imageProcessingConfiguration.contrast;
  84963. },
  84964. /**
  84965. * Sets The camera contrast used on this material.
  84966. */
  84967. set: function (value) {
  84968. this._imageProcessingConfiguration.contrast = value;
  84969. },
  84970. enumerable: true,
  84971. configurable: true
  84972. });
  84973. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  84974. /**
  84975. * Gets the Color Grading 2D Lookup Texture.
  84976. */
  84977. get: function () {
  84978. return this._imageProcessingConfiguration.colorGradingTexture;
  84979. },
  84980. /**
  84981. * Sets the Color Grading 2D Lookup Texture.
  84982. */
  84983. set: function (value) {
  84984. this.imageProcessingConfiguration.colorGradingTexture = value;
  84985. },
  84986. enumerable: true,
  84987. configurable: true
  84988. });
  84989. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  84990. /**
  84991. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  84992. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  84993. * 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;
  84994. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  84995. */
  84996. get: function () {
  84997. return this.imageProcessingConfiguration.colorCurves;
  84998. },
  84999. /**
  85000. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  85001. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  85002. * 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;
  85003. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  85004. */
  85005. set: function (value) {
  85006. this.imageProcessingConfiguration.colorCurves = value;
  85007. },
  85008. enumerable: true,
  85009. configurable: true
  85010. });
  85011. /**
  85012. * The entire material has been created in order to prevent overdraw.
  85013. * @returns false
  85014. */
  85015. BackgroundMaterial.prototype.needAlphaTesting = function () {
  85016. return true;
  85017. };
  85018. /**
  85019. * The entire material has been created in order to prevent overdraw.
  85020. * @returns true if blending is enable
  85021. */
  85022. BackgroundMaterial.prototype.needAlphaBlending = function () {
  85023. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  85024. };
  85025. /**
  85026. * Checks wether the material is ready to be rendered for a given mesh.
  85027. * @param mesh The mesh to render
  85028. * @param subMesh The submesh to check against
  85029. * @param useInstances Specify wether or not the material is used with instances
  85030. * @returns true if all the dependencies are ready (Textures, Effects...)
  85031. */
  85032. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  85033. var _this = this;
  85034. if (useInstances === void 0) { useInstances = false; }
  85035. if (subMesh.effect && this.isFrozen) {
  85036. if (this._wasPreviouslyReady) {
  85037. return true;
  85038. }
  85039. }
  85040. if (!subMesh._materialDefines) {
  85041. subMesh._materialDefines = new BackgroundMaterialDefines();
  85042. }
  85043. var scene = this.getScene();
  85044. var defines = subMesh._materialDefines;
  85045. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  85046. if (defines._renderId === scene.getRenderId()) {
  85047. return true;
  85048. }
  85049. }
  85050. var engine = scene.getEngine();
  85051. // Lights
  85052. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  85053. defines._needNormals = true;
  85054. // Textures
  85055. if (defines._areTexturesDirty) {
  85056. defines._needUVs = false;
  85057. if (scene.texturesEnabled) {
  85058. if (scene.getEngine().getCaps().textureLOD) {
  85059. defines.TEXTURELODSUPPORT = true;
  85060. }
  85061. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  85062. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  85063. return false;
  85064. }
  85065. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  85066. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  85067. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  85068. defines.OPACITYFRESNEL = this._opacityFresnel;
  85069. }
  85070. else {
  85071. defines.DIFFUSE = false;
  85072. defines.DIFFUSEHASALPHA = false;
  85073. defines.GAMMADIFFUSE = false;
  85074. defines.OPACITYFRESNEL = false;
  85075. }
  85076. var reflectionTexture = this._reflectionTexture;
  85077. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  85078. if (!reflectionTexture.isReadyOrNotBlocking()) {
  85079. return false;
  85080. }
  85081. defines.REFLECTION = true;
  85082. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  85083. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  85084. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  85085. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  85086. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  85087. defines.INVERTCUBICMAP = true;
  85088. }
  85089. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  85090. switch (reflectionTexture.coordinatesMode) {
  85091. case BABYLON.Texture.CUBIC_MODE:
  85092. case BABYLON.Texture.INVCUBIC_MODE:
  85093. defines.REFLECTIONMAP_CUBIC = true;
  85094. break;
  85095. case BABYLON.Texture.EXPLICIT_MODE:
  85096. defines.REFLECTIONMAP_EXPLICIT = true;
  85097. break;
  85098. case BABYLON.Texture.PLANAR_MODE:
  85099. defines.REFLECTIONMAP_PLANAR = true;
  85100. break;
  85101. case BABYLON.Texture.PROJECTION_MODE:
  85102. defines.REFLECTIONMAP_PROJECTION = true;
  85103. break;
  85104. case BABYLON.Texture.SKYBOX_MODE:
  85105. defines.REFLECTIONMAP_SKYBOX = true;
  85106. break;
  85107. case BABYLON.Texture.SPHERICAL_MODE:
  85108. defines.REFLECTIONMAP_SPHERICAL = true;
  85109. break;
  85110. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  85111. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  85112. break;
  85113. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  85114. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  85115. break;
  85116. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  85117. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  85118. break;
  85119. }
  85120. if (this.reflectionFresnel) {
  85121. defines.REFLECTIONFRESNEL = true;
  85122. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  85123. this._reflectionControls.x = this.reflectionAmount;
  85124. this._reflectionControls.y = this.reflectionReflectance0;
  85125. this._reflectionControls.z = this.reflectionReflectance90;
  85126. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  85127. }
  85128. else {
  85129. defines.REFLECTIONFRESNEL = false;
  85130. defines.REFLECTIONFALLOFF = false;
  85131. }
  85132. }
  85133. else {
  85134. defines.REFLECTION = false;
  85135. defines.REFLECTIONFALLOFF = false;
  85136. defines.REFLECTIONBLUR = false;
  85137. defines.REFLECTIONMAP_3D = false;
  85138. defines.REFLECTIONMAP_SPHERICAL = false;
  85139. defines.REFLECTIONMAP_PLANAR = false;
  85140. defines.REFLECTIONMAP_CUBIC = false;
  85141. defines.REFLECTIONMAP_PROJECTION = false;
  85142. defines.REFLECTIONMAP_SKYBOX = false;
  85143. defines.REFLECTIONMAP_EXPLICIT = false;
  85144. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  85145. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  85146. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  85147. defines.INVERTCUBICMAP = false;
  85148. defines.REFLECTIONMAP_OPPOSITEZ = false;
  85149. defines.LODINREFLECTIONALPHA = false;
  85150. defines.GAMMAREFLECTION = false;
  85151. }
  85152. }
  85153. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  85154. defines.USERGBCOLOR = this._useRGBColor;
  85155. defines.NOISE = this._enableNoise;
  85156. }
  85157. if (defines._areImageProcessingDirty) {
  85158. if (!this._imageProcessingConfiguration.isReady()) {
  85159. return false;
  85160. }
  85161. this._imageProcessingConfiguration.prepareDefines(defines);
  85162. }
  85163. // Misc.
  85164. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  85165. // Values that need to be evaluated on every frame
  85166. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  85167. // Attribs
  85168. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  85169. if (mesh) {
  85170. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85171. mesh.createNormals(true);
  85172. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  85173. }
  85174. }
  85175. }
  85176. // Get correct effect
  85177. if (defines.isDirty) {
  85178. defines.markAsProcessed();
  85179. scene.resetCachedMaterial();
  85180. // Fallbacks
  85181. var fallbacks = new BABYLON.EffectFallbacks();
  85182. if (defines.FOG) {
  85183. fallbacks.addFallback(0, "FOG");
  85184. }
  85185. if (defines.POINTSIZE) {
  85186. fallbacks.addFallback(1, "POINTSIZE");
  85187. }
  85188. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  85189. if (defines.NUM_BONE_INFLUENCERS > 0) {
  85190. fallbacks.addCPUSkinningFallback(0, mesh);
  85191. }
  85192. //Attributes
  85193. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85194. if (defines.NORMAL) {
  85195. attribs.push(BABYLON.VertexBuffer.NormalKind);
  85196. }
  85197. if (defines.UV1) {
  85198. attribs.push(BABYLON.VertexBuffer.UVKind);
  85199. }
  85200. if (defines.UV2) {
  85201. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85202. }
  85203. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  85204. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  85205. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  85206. "vFogInfos", "vFogColor", "pointSize",
  85207. "vClipPlane", "mBones",
  85208. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  85209. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  85210. "shadowLevel", "alpha",
  85211. "vBackgroundCenter", "vReflectionControl",
  85212. "vDiffuseInfos", "diffuseMatrix",
  85213. ];
  85214. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  85215. var uniformBuffers = ["Material", "Scene"];
  85216. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  85217. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  85218. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  85219. uniformsNames: uniforms,
  85220. uniformBuffersNames: uniformBuffers,
  85221. samplers: samplers,
  85222. defines: defines,
  85223. maxSimultaneousLights: this._maxSimultaneousLights
  85224. });
  85225. var onCompiled = function (effect) {
  85226. if (_this.onCompiled) {
  85227. _this.onCompiled(effect);
  85228. }
  85229. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  85230. };
  85231. var join = defines.toString();
  85232. subMesh.setEffect(scene.getEngine().createEffect("background", {
  85233. attributes: attribs,
  85234. uniformsNames: uniforms,
  85235. uniformBuffersNames: uniformBuffers,
  85236. samplers: samplers,
  85237. defines: join,
  85238. fallbacks: fallbacks,
  85239. onCompiled: onCompiled,
  85240. onError: this.onError,
  85241. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  85242. }, engine), defines);
  85243. this.buildUniformLayout();
  85244. }
  85245. if (!subMesh.effect || !subMesh.effect.isReady()) {
  85246. return false;
  85247. }
  85248. defines._renderId = scene.getRenderId();
  85249. this._wasPreviouslyReady = true;
  85250. return true;
  85251. };
  85252. /**
  85253. * Build the uniform buffer used in the material.
  85254. */
  85255. BackgroundMaterial.prototype.buildUniformLayout = function () {
  85256. // Order is important !
  85257. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  85258. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  85259. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  85260. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  85261. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  85262. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  85263. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  85264. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  85265. this._uniformBuffer.addUniform("pointSize", 1);
  85266. this._uniformBuffer.addUniform("shadowLevel", 1);
  85267. this._uniformBuffer.addUniform("alpha", 1);
  85268. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  85269. this._uniformBuffer.addUniform("vReflectionControl", 4);
  85270. this._uniformBuffer.create();
  85271. };
  85272. /**
  85273. * Unbind the material.
  85274. */
  85275. BackgroundMaterial.prototype.unbind = function () {
  85276. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  85277. this._uniformBuffer.setTexture("diffuseSampler", null);
  85278. }
  85279. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  85280. this._uniformBuffer.setTexture("reflectionSampler", null);
  85281. }
  85282. _super.prototype.unbind.call(this);
  85283. };
  85284. /**
  85285. * Bind only the world matrix to the material.
  85286. * @param world The world matrix to bind.
  85287. */
  85288. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  85289. this._activeEffect.setMatrix("world", world);
  85290. };
  85291. /**
  85292. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  85293. * @param world The world matrix to bind.
  85294. * @param subMesh The submesh to bind for.
  85295. */
  85296. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  85297. var scene = this.getScene();
  85298. var defines = subMesh._materialDefines;
  85299. if (!defines) {
  85300. return;
  85301. }
  85302. var effect = subMesh.effect;
  85303. if (!effect) {
  85304. return;
  85305. }
  85306. this._activeEffect = effect;
  85307. // Matrices
  85308. this.bindOnlyWorldMatrix(world);
  85309. // Bones
  85310. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  85311. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  85312. if (mustRebind) {
  85313. this._uniformBuffer.bindToEffect(effect, "Material");
  85314. this.bindViewProjection(effect);
  85315. var reflectionTexture = this._reflectionTexture;
  85316. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  85317. // Texture uniforms
  85318. if (scene.texturesEnabled) {
  85319. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  85320. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  85321. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  85322. }
  85323. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  85324. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  85325. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  85326. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  85327. }
  85328. }
  85329. if (this.shadowLevel > 0) {
  85330. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  85331. }
  85332. this._uniformBuffer.updateFloat("alpha", this.alpha);
  85333. // Point size
  85334. if (this.pointsCloud) {
  85335. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  85336. }
  85337. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  85338. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  85339. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  85340. }
  85341. // Textures
  85342. if (scene.texturesEnabled) {
  85343. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  85344. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  85345. }
  85346. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  85347. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  85348. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  85349. }
  85350. else if (!defines.REFLECTIONBLUR) {
  85351. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  85352. }
  85353. else {
  85354. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  85355. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  85356. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  85357. }
  85358. if (defines.REFLECTIONFRESNEL) {
  85359. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  85360. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  85361. }
  85362. }
  85363. }
  85364. // Clip plane
  85365. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  85366. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  85367. }
  85368. if (mustRebind || !this.isFrozen) {
  85369. if (scene.lightsEnabled) {
  85370. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  85371. }
  85372. // View
  85373. this.bindView(effect);
  85374. // Fog
  85375. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  85376. // image processing
  85377. this._imageProcessingConfiguration.bind(this._activeEffect);
  85378. }
  85379. this._uniformBuffer.update();
  85380. this._afterBind(mesh);
  85381. };
  85382. /**
  85383. * Dispose the material.
  85384. * @param forceDisposeEffect Force disposal of the associated effect.
  85385. * @param forceDisposeTextures Force disposal of the associated textures.
  85386. */
  85387. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  85388. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  85389. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  85390. if (forceDisposeTextures) {
  85391. if (this.diffuseTexture) {
  85392. this.diffuseTexture.dispose();
  85393. }
  85394. if (this.reflectionTexture) {
  85395. this.reflectionTexture.dispose();
  85396. }
  85397. }
  85398. this._renderTargets.dispose();
  85399. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  85400. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  85401. }
  85402. _super.prototype.dispose.call(this, forceDisposeEffect);
  85403. };
  85404. /**
  85405. * Clones the material.
  85406. * @param name The cloned name.
  85407. * @returns The cloned material.
  85408. */
  85409. BackgroundMaterial.prototype.clone = function (name) {
  85410. var _this = this;
  85411. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  85412. };
  85413. /**
  85414. * Serializes the current material to its JSON representation.
  85415. * @returns The JSON representation.
  85416. */
  85417. BackgroundMaterial.prototype.serialize = function () {
  85418. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85419. serializationObject.customType = "BABYLON.BackgroundMaterial";
  85420. return serializationObject;
  85421. };
  85422. /**
  85423. * Gets the class name of the material
  85424. * @returns "BackgroundMaterial"
  85425. */
  85426. BackgroundMaterial.prototype.getClassName = function () {
  85427. return "BackgroundMaterial";
  85428. };
  85429. /**
  85430. * Parse a JSON input to create back a background material.
  85431. * @param source The JSON data to parse
  85432. * @param scene The scene to create the parsed material in
  85433. * @param rootUrl The root url of the assets the material depends upon
  85434. * @returns the instantiated BackgroundMaterial.
  85435. */
  85436. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  85437. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  85438. };
  85439. /**
  85440. * Standard reflectance value at parallel view angle.
  85441. */
  85442. BackgroundMaterial.StandardReflectance0 = 0.05;
  85443. /**
  85444. * Standard reflectance value at grazing angle.
  85445. */
  85446. BackgroundMaterial.StandardReflectance90 = 0.5;
  85447. __decorate([
  85448. BABYLON.serializeAsColor3()
  85449. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  85450. __decorate([
  85451. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  85452. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  85453. __decorate([
  85454. BABYLON.serialize()
  85455. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  85456. __decorate([
  85457. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  85458. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  85459. __decorate([
  85460. BABYLON.serializeAsColor3()
  85461. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  85462. __decorate([
  85463. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  85464. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  85465. __decorate([
  85466. BABYLON.serialize()
  85467. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  85468. __decorate([
  85469. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  85470. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  85471. __decorate([
  85472. BABYLON.serializeAsColor3()
  85473. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  85474. __decorate([
  85475. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  85476. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  85477. __decorate([
  85478. BABYLON.serialize()
  85479. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  85480. __decorate([
  85481. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  85482. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  85483. __decorate([
  85484. BABYLON.serializeAsTexture()
  85485. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  85486. __decorate([
  85487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85488. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  85489. __decorate([
  85490. BABYLON.serialize()
  85491. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  85492. __decorate([
  85493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85494. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  85495. __decorate([
  85496. BABYLON.serializeAsTexture()
  85497. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  85498. __decorate([
  85499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85500. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  85501. __decorate([
  85502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85503. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  85504. __decorate([
  85505. BABYLON.serialize()
  85506. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  85507. __decorate([
  85508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85509. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  85510. __decorate([
  85511. BABYLON.serialize()
  85512. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  85513. __decorate([
  85514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85515. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  85516. __decorate([
  85517. BABYLON.serializeAsVector3()
  85518. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  85519. __decorate([
  85520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85521. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  85522. __decorate([
  85523. BABYLON.serialize()
  85524. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  85525. __decorate([
  85526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85527. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  85528. __decorate([
  85529. BABYLON.serialize()
  85530. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  85531. __decorate([
  85532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85533. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  85534. __decorate([
  85535. BABYLON.serialize()
  85536. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  85537. __decorate([
  85538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85539. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  85540. __decorate([
  85541. BABYLON.serialize()
  85542. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  85543. __decorate([
  85544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85545. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  85546. __decorate([
  85547. BABYLON.serialize()
  85548. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  85549. __decorate([
  85550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85551. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  85552. __decorate([
  85553. BABYLON.serialize()
  85554. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  85555. __decorate([
  85556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85557. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  85558. __decorate([
  85559. BABYLON.serialize()
  85560. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  85561. __decorate([
  85562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85563. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  85564. __decorate([
  85565. BABYLON.serialize()
  85566. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  85567. __decorate([
  85568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85569. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  85570. __decorate([
  85571. BABYLON.serialize()
  85572. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  85573. __decorate([
  85574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  85575. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  85576. __decorate([
  85577. BABYLON.serializeAsImageProcessingConfiguration()
  85578. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  85579. return BackgroundMaterial;
  85580. }(BABYLON.PushMaterial));
  85581. BABYLON.BackgroundMaterial = BackgroundMaterial;
  85582. })(BABYLON || (BABYLON = {}));
  85583. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  85584. var __assign = (this && this.__assign) || Object.assign || function(t) {
  85585. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85586. s = arguments[i];
  85587. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85588. t[p] = s[p];
  85589. }
  85590. return t;
  85591. };
  85592. var BABYLON;
  85593. (function (BABYLON) {
  85594. /**
  85595. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  85596. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  85597. * It also helps with the default setup of your imageProcessing configuration.
  85598. */
  85599. var EnvironmentHelper = /** @class */ (function () {
  85600. /**
  85601. * constructor
  85602. * @param options
  85603. * @param scene The scene to add the material to
  85604. */
  85605. function EnvironmentHelper(options, scene) {
  85606. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  85607. this._scene = scene;
  85608. this._setupBackground();
  85609. this._setupImageProcessing();
  85610. }
  85611. /**
  85612. * Creates the default options for the helper.
  85613. */
  85614. EnvironmentHelper._getDefaultOptions = function () {
  85615. return {
  85616. createGround: true,
  85617. groundSize: 15,
  85618. groundTexture: this._groundTextureCDNUrl,
  85619. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  85620. groundOpacity: 0.9,
  85621. enableGroundShadow: true,
  85622. groundShadowLevel: 0.5,
  85623. enableGroundMirror: false,
  85624. groundMirrorSizeRatio: 0.3,
  85625. groundMirrorBlurKernel: 64,
  85626. groundMirrorAmount: 1,
  85627. groundMirrorFresnelWeight: 1,
  85628. groundMirrorFallOffDistance: 0,
  85629. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  85630. groundYBias: 0.00001,
  85631. createSkybox: true,
  85632. skyboxSize: 20,
  85633. skyboxTexture: this._skyboxTextureCDNUrl,
  85634. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  85635. backgroundYRotation: 0,
  85636. sizeAuto: true,
  85637. rootPosition: BABYLON.Vector3.Zero(),
  85638. setupImageProcessing: true,
  85639. environmentTexture: this._environmentTextureCDNUrl,
  85640. cameraExposure: 0.8,
  85641. cameraContrast: 1.2,
  85642. toneMappingEnabled: true,
  85643. };
  85644. };
  85645. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  85646. /**
  85647. * Gets the root mesh created by the helper.
  85648. */
  85649. get: function () {
  85650. return this._rootMesh;
  85651. },
  85652. enumerable: true,
  85653. configurable: true
  85654. });
  85655. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  85656. /**
  85657. * Gets the skybox created by the helper.
  85658. */
  85659. get: function () {
  85660. return this._skybox;
  85661. },
  85662. enumerable: true,
  85663. configurable: true
  85664. });
  85665. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  85666. /**
  85667. * Gets the skybox texture created by the helper.
  85668. */
  85669. get: function () {
  85670. return this._skyboxTexture;
  85671. },
  85672. enumerable: true,
  85673. configurable: true
  85674. });
  85675. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  85676. /**
  85677. * Gets the skybox material created by the helper.
  85678. */
  85679. get: function () {
  85680. return this._skyboxMaterial;
  85681. },
  85682. enumerable: true,
  85683. configurable: true
  85684. });
  85685. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  85686. /**
  85687. * Gets the ground mesh created by the helper.
  85688. */
  85689. get: function () {
  85690. return this._ground;
  85691. },
  85692. enumerable: true,
  85693. configurable: true
  85694. });
  85695. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  85696. /**
  85697. * Gets the ground texture created by the helper.
  85698. */
  85699. get: function () {
  85700. return this._groundTexture;
  85701. },
  85702. enumerable: true,
  85703. configurable: true
  85704. });
  85705. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  85706. /**
  85707. * Gets the ground mirror created by the helper.
  85708. */
  85709. get: function () {
  85710. return this._groundMirror;
  85711. },
  85712. enumerable: true,
  85713. configurable: true
  85714. });
  85715. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  85716. /**
  85717. * Gets the ground mirror render list to helps pushing the meshes
  85718. * you wish in the ground reflection.
  85719. */
  85720. get: function () {
  85721. if (this._groundMirror) {
  85722. return this._groundMirror.renderList;
  85723. }
  85724. return null;
  85725. },
  85726. enumerable: true,
  85727. configurable: true
  85728. });
  85729. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  85730. /**
  85731. * Gets the ground material created by the helper.
  85732. */
  85733. get: function () {
  85734. return this._groundMaterial;
  85735. },
  85736. enumerable: true,
  85737. configurable: true
  85738. });
  85739. /**
  85740. * Updates the background according to the new options
  85741. * @param options
  85742. */
  85743. EnvironmentHelper.prototype.updateOptions = function (options) {
  85744. var newOptions = __assign({}, this._options, options);
  85745. if (this._ground && !newOptions.createGround) {
  85746. this._ground.dispose();
  85747. this._ground = null;
  85748. }
  85749. if (this._groundMaterial && !newOptions.createGround) {
  85750. this._groundMaterial.dispose();
  85751. this._groundMaterial = null;
  85752. }
  85753. if (this._groundTexture) {
  85754. if (this._options.groundTexture != newOptions.groundTexture) {
  85755. this._groundTexture.dispose();
  85756. this._groundTexture = null;
  85757. }
  85758. }
  85759. if (this._skybox && !newOptions.createSkybox) {
  85760. this._skybox.dispose();
  85761. this._skybox = null;
  85762. }
  85763. if (this._skyboxMaterial && !newOptions.createSkybox) {
  85764. this._skyboxMaterial.dispose();
  85765. this._skyboxMaterial = null;
  85766. }
  85767. if (this._skyboxTexture) {
  85768. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  85769. this._skyboxTexture.dispose();
  85770. this._skyboxTexture = null;
  85771. }
  85772. }
  85773. if (this._groundMirror && !newOptions.enableGroundMirror) {
  85774. this._groundMirror.dispose();
  85775. this._groundMirror = null;
  85776. }
  85777. if (this._scene.environmentTexture) {
  85778. if (this._options.environmentTexture != newOptions.environmentTexture) {
  85779. this._scene.environmentTexture.dispose();
  85780. }
  85781. }
  85782. this._options = newOptions;
  85783. this._setupBackground();
  85784. this._setupImageProcessing();
  85785. };
  85786. /**
  85787. * Sets the primary color of all the available elements.
  85788. * @param color
  85789. */
  85790. EnvironmentHelper.prototype.setMainColor = function (color) {
  85791. if (this.groundMaterial) {
  85792. this.groundMaterial.primaryColor = color;
  85793. }
  85794. if (this.skyboxMaterial) {
  85795. this.skyboxMaterial.primaryColor = color;
  85796. }
  85797. if (this.groundMirror) {
  85798. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  85799. }
  85800. };
  85801. /**
  85802. * Setup the image processing according to the specified options.
  85803. */
  85804. EnvironmentHelper.prototype._setupImageProcessing = function () {
  85805. if (this._options.setupImageProcessing) {
  85806. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  85807. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  85808. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  85809. this._setupEnvironmentTexture();
  85810. }
  85811. };
  85812. /**
  85813. * Setup the environment texture according to the specified options.
  85814. */
  85815. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  85816. if (this._scene.environmentTexture) {
  85817. return;
  85818. }
  85819. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  85820. this._scene.environmentTexture = this._options.environmentTexture;
  85821. return;
  85822. }
  85823. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  85824. this._scene.environmentTexture = environmentTexture;
  85825. };
  85826. /**
  85827. * Setup the background according to the specified options.
  85828. */
  85829. EnvironmentHelper.prototype._setupBackground = function () {
  85830. if (!this._rootMesh) {
  85831. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  85832. }
  85833. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  85834. var sceneSize = this._getSceneSize();
  85835. if (this._options.createGround) {
  85836. this._setupGround(sceneSize);
  85837. this._setupGroundMaterial();
  85838. this._setupGroundDiffuseTexture();
  85839. if (this._options.enableGroundMirror) {
  85840. this._setupGroundMirrorTexture(sceneSize);
  85841. }
  85842. this._setupMirrorInGroundMaterial();
  85843. }
  85844. if (this._options.createSkybox) {
  85845. this._setupSkybox(sceneSize);
  85846. this._setupSkyboxMaterial();
  85847. this._setupSkyboxReflectionTexture();
  85848. }
  85849. this._rootMesh.position.x = sceneSize.rootPosition.x;
  85850. this._rootMesh.position.z = sceneSize.rootPosition.z;
  85851. this._rootMesh.position.y = sceneSize.rootPosition.y;
  85852. };
  85853. /**
  85854. * Get the scene sizes according to the setup.
  85855. */
  85856. EnvironmentHelper.prototype._getSceneSize = function () {
  85857. var groundSize = this._options.groundSize;
  85858. var skyboxSize = this._options.skyboxSize;
  85859. var rootPosition = this._options.rootPosition;
  85860. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  85861. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  85862. }
  85863. var sceneExtends = this._scene.getWorldExtends();
  85864. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  85865. if (this._options.sizeAuto) {
  85866. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  85867. this._scene.activeCamera.upperRadiusLimit) {
  85868. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  85869. skyboxSize = groundSize;
  85870. }
  85871. var sceneDiagonalLenght = sceneDiagonal.length();
  85872. if (sceneDiagonalLenght > groundSize) {
  85873. groundSize = sceneDiagonalLenght * 2;
  85874. skyboxSize = groundSize;
  85875. }
  85876. // 10 % bigger.
  85877. groundSize *= 1.1;
  85878. skyboxSize *= 1.5;
  85879. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  85880. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  85881. }
  85882. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  85883. };
  85884. /**
  85885. * Setup the ground according to the specified options.
  85886. */
  85887. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  85888. var _this = this;
  85889. if (!this._ground) {
  85890. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  85891. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  85892. this._ground.parent = this._rootMesh;
  85893. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  85894. }
  85895. this._ground.receiveShadows = this._options.enableGroundShadow;
  85896. };
  85897. /**
  85898. * Setup the ground material according to the specified options.
  85899. */
  85900. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  85901. if (!this._groundMaterial) {
  85902. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  85903. }
  85904. this._groundMaterial.alpha = this._options.groundOpacity;
  85905. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  85906. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  85907. this._groundMaterial.primaryLevel = 1;
  85908. this._groundMaterial.primaryColor = this._options.groundColor;
  85909. this._groundMaterial.secondaryLevel = 0;
  85910. this._groundMaterial.tertiaryLevel = 0;
  85911. this._groundMaterial.useRGBColor = false;
  85912. this._groundMaterial.enableNoise = true;
  85913. if (this._ground) {
  85914. this._ground.material = this._groundMaterial;
  85915. }
  85916. };
  85917. /**
  85918. * Setup the ground diffuse texture according to the specified options.
  85919. */
  85920. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  85921. if (!this._groundMaterial) {
  85922. return;
  85923. }
  85924. if (this._groundTexture) {
  85925. return;
  85926. }
  85927. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  85928. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  85929. return;
  85930. }
  85931. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  85932. diffuseTexture.gammaSpace = false;
  85933. diffuseTexture.hasAlpha = true;
  85934. this._groundMaterial.diffuseTexture = diffuseTexture;
  85935. };
  85936. /**
  85937. * Setup the ground mirror texture according to the specified options.
  85938. */
  85939. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  85940. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85941. if (!this._groundMirror) {
  85942. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  85943. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  85944. this._groundMirror.anisotropicFilteringLevel = 1;
  85945. this._groundMirror.wrapU = wrapping;
  85946. this._groundMirror.wrapV = wrapping;
  85947. this._groundMirror.gammaSpace = false;
  85948. if (this._groundMirror.renderList) {
  85949. for (var i = 0; i < this._scene.meshes.length; i++) {
  85950. var mesh = this._scene.meshes[i];
  85951. if (mesh !== this._ground &&
  85952. mesh !== this._skybox &&
  85953. mesh !== this._rootMesh) {
  85954. this._groundMirror.renderList.push(mesh);
  85955. }
  85956. }
  85957. }
  85958. }
  85959. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  85960. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  85961. };
  85962. /**
  85963. * Setup the ground to receive the mirror texture.
  85964. */
  85965. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  85966. if (this._groundMaterial) {
  85967. this._groundMaterial.reflectionTexture = this._groundMirror;
  85968. this._groundMaterial.reflectionFresnel = true;
  85969. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  85970. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  85971. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  85972. }
  85973. };
  85974. /**
  85975. * Setup the skybox according to the specified options.
  85976. */
  85977. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  85978. var _this = this;
  85979. if (!this._skybox) {
  85980. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  85981. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  85982. }
  85983. this._skybox.parent = this._rootMesh;
  85984. };
  85985. /**
  85986. * Setup the skybox material according to the specified options.
  85987. */
  85988. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  85989. if (!this._skybox) {
  85990. return;
  85991. }
  85992. if (!this._skyboxMaterial) {
  85993. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  85994. }
  85995. this._skyboxMaterial.useRGBColor = false;
  85996. this._skyboxMaterial.primaryLevel = 1;
  85997. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  85998. this._skyboxMaterial.secondaryLevel = 0;
  85999. this._skyboxMaterial.tertiaryLevel = 0;
  86000. this._skyboxMaterial.enableNoise = true;
  86001. this._skybox.material = this._skyboxMaterial;
  86002. };
  86003. /**
  86004. * Setup the skybox reflection texture according to the specified options.
  86005. */
  86006. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  86007. if (!this._skyboxMaterial) {
  86008. return;
  86009. }
  86010. if (this._skyboxTexture) {
  86011. return;
  86012. }
  86013. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  86014. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  86015. return;
  86016. }
  86017. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  86018. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  86019. this._skyboxTexture.gammaSpace = false;
  86020. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  86021. };
  86022. /**
  86023. * Dispose all the elements created by the Helper.
  86024. */
  86025. EnvironmentHelper.prototype.dispose = function () {
  86026. if (this._groundMaterial) {
  86027. this._groundMaterial.dispose(true, true);
  86028. }
  86029. if (this._skyboxMaterial) {
  86030. this._skyboxMaterial.dispose(true, true);
  86031. }
  86032. this._rootMesh.dispose(false);
  86033. };
  86034. /**
  86035. * Default ground texture URL.
  86036. */
  86037. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  86038. /**
  86039. * Default skybox texture URL.
  86040. */
  86041. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  86042. /**
  86043. * Default environment texture URL.
  86044. */
  86045. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  86046. return EnvironmentHelper;
  86047. }());
  86048. BABYLON.EnvironmentHelper = EnvironmentHelper;
  86049. })(BABYLON || (BABYLON = {}));
  86050. //# sourceMappingURL=babylon.environmentHelper.js.map
  86051. 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}","gpuRenderParticlesVertexShader":"#version 300 es\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\nvoid main() {\ngl_PointSize=1.0;\ngl_Position=vec4(position,1.0);\n}","gpuRenderParticlesPixelShader":"void main() {\ngl_FragColor=vec4(1.0);\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\nuniform float timeDelta;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec3 outVelocity;\nvoid main() {\nif (age>=life) {\n\noutPosition=vec3(0,0,0);\n\noutAge=0.0;\noutLife=life;\n\noutVelocity=vec3(0,1,0);\n} else {\noutPosition=position+velocity*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutVelocity=velocity;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,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}"};
  86052. 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};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  86053. globalObject["BABYLON"] = BABYLON;
  86054. 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 GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var 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 NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;
  86055. 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,GPUParticleSystem,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,DepthOfFieldBlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,HighlightLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper };